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 operation
  • 3 = AND operation
  • 4 = XOR operation
  • 5 = 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
Minimum Flips in Binary Tree to Get Result INPUT Binary Expression Tree OR (2) 0 false 1 true Input Array: 2 0 1 Desired Result: false Current: OR(0,1) = true ALGORITHM STEPS 1 DFS with DP Compute cost to make each subtree evaluate to 0 or 1 2 Leaf Node Base Case cost[0]=0 if val=0, else 1 cost[1]=0 if val=1, else 1 3 OR Node Logic cost[0]=L[0]+R[0] (both 0) cost[1]=min ways to get 1 4 Compute for Root Return root cost[result] DP Costs Table: Node cost[0] cost[1] L(0) 0 1 R(1) 1 0 OR 1 0 FINAL RESULT After 1 Flip: OR 0 0 FLIP! 1 --> 0 OR(0, 0) = false Output: 1 OK - Minimum flips = 1 Result achieved: false Key Insight: Use tree DP: For each node, compute minimum flips to make subtree evaluate to 0 or 1. For OR: cost[0] = L[0]+R[0] (both must be 0), cost[1] = min(L[1]+R[0], L[0]+R[1], L[1]+R[1]) TutorialsPoint - Minimum Flips in Binary Tree to Get Result | Optimal Solution (Tree DP)
Asked in
Google 45 Microsoft 32 Meta 28 Amazon 24
36.7K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen