638. Minimum Flips In Binary Tree to Get Result

The root of a binary tree with the following attributes is provided to you:

  • False and true are represented by the values 0 and 1, respectively, for leaf nodes.
  • The boolean operations OR, AND, XOR, and NOT are represented by the values 2, 3, 4, and 5, respectively, for non-leaf nodes.

Additionally, a boolean result—the intended outcome of the root node evaluation—is provided to you.

The following is how a node is evaluated:

  • The evaluation is the node's value, which can be either true or false if the node is a leaf node.
  • If not, assess the node's offspring and use the boolean operation of its value in conjunction with the assessments of the offspring.

In a single action, you can flip a leaf node, making a true node false and a false node true.

Give back the bare minimum of steps required to ensure that the evaluation of root yields results. It can be demonstrated that a solution is always possible.

A leaf node is a node that has zero children.

Note : NOT nodes have either a left child or a right child, but other non-leaf nodes have both a left child and a right child.

Example 1:

Input : root = [2, 4, 3, 5, 1, 0, 0, 1] , result = false

Output : 1

Explanation :

We can flip the value of leaf node attached to node with value 5.

Example 2:

Input : root = [3,5,4,2,null,1,1,1,0], result = true

Output : 2

Explanation :

We can flip the value of leaf node under node with value 2 from true to false.

in 2nd operation we flip the leaf node under node with value 4 from true to false.

Now Your Turn!

Pick the correct output for the given input

Input : root = [2, 4, 3, 5, 2, 0, 5, 1, null, 0, 1, null, null, 0], result = false

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 0 <= Node.val <= 5
  • OR, AND, and XOR nodes have 2 children.
  • NOT nodes have 1 child.
  • Leaf nodes have a value of 0 or 1.
  • Non-leaf nodes have a value of 2, 3, 4, or 5.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
int minimumFlips(TreeNode* root, bool result) {
//your code goes here
}
};
Test Case

Input:

Result
Root