Minimum Flips in Binary Tree to Get Result - Problem
Imagine you have a binary expression tree where each leaf contains a boolean value (0 for false, 1 for true) and each internal node represents a boolean operation:
2= OR operation3= AND operation4= XOR operation5= NOT operation (has only one child)
Your goal is to find the minimum number of leaf flips needed to make the entire tree evaluate to a desired result. A flip changes 0→1 or 1→0.
Key Challenge: You need to work backwards from the root, determining what each subtree should evaluate to in order to achieve the target result with minimum flips.
Input & Output
example_1.py — Basic OR Operation
$
Input:
root = [2,0,1], result = false
Tree: OR(0,1)
›
Output:
1
💡 Note:
The tree evaluates to true (0 OR 1 = true). To get false, we need both children false, so flip the right child: 1 flip needed.
example_2.py — AND with XOR
$
Input:
root = [3,4,[0,1],1], result = true
Tree: AND(XOR(0,1),1)
›
Output:
0
💡 Note:
XOR(0,1) = true, AND(true,1) = true. Already evaluates to true, so 0 flips needed.
example_3.py — NOT Operation
$
Input:
root = [5,0], result = true
Tree: NOT(0)
›
Output:
0
💡 Note:
NOT(0) = true. Already evaluates to the desired result, so 0 flips needed.
Constraints
- The number of nodes in the tree is in the range [1, 105]
- Node values: 0, 1 for leaves, 2, 3, 4, 5 for internal nodes
- NOT nodes have exactly one child, others have exactly two children
- Leaf nodes have values 0 or 1 only
- It is guaranteed that result can always be achieved
Visualization
Tap to expand
Understanding the Visualization
1
Identify Structure
Map out the boolean operations tree with leaves as switches
2
Calculate Leaf Costs
For each switch, determine flip cost for true/false
3
Combine Gate Costs
Work upward, calculating optimal costs for each gate
4
Find Optimal Path
Choose the minimum cost path to desired output
Key Takeaway
🎯 Key Insight: By calculating costs for both true and false outcomes at each node, we can optimally combine paths and avoid exploring all exponential possibilities, reducing complexity from O(2^n) to O(n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code