Leetcode #2313: Minimum Flips in Binary Tree to Get Result
In this guide, we solve Leetcode #2313 Minimum Flips in Binary Tree to Get Result in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given the root of a binary tree with the following properties: Leaf nodes have either the value 0 or 1, representing false and true respectively. Non-leaf nodes have either the value 2, 3, 4, or 5, representing the boolean operations OR, AND, XOR, and NOT, respectively.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Tree, Depth-First Search, Dynamic Programming, Binary Tree
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: root = [3,5,4,2,null,1,1,1,0], result = true
Output: 2
Explanation:
It can be shown that a minimum of 2 nodes have to be flipped to make the root of the tree
evaluate to true. One way to achieve this is shown in the diagram above.
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minimumFlips(self, root: Optional[TreeNode], result: bool) -> int:
def dfs(root: Optional[TreeNode]) -> (int, int):
if root is None:
return inf, inf
x = root.val
if x in (0, 1):
return x, x ^ 1
l, r = dfs(root.left), dfs(root.right)
if x == 2:
return l[0] + r[0], min(l[0] + r[1], l[1] + r[0], l[1] + r[1])
if x == 3:
return min(l[0] + r[0], l[0] + r[1], l[1] + r[0]), l[1] + r[1]
if x == 4:
return min(l[0] + r[0], l[1] + r[1]), min(l[0] + r[1], l[1] + r[0])
return min(l[1], r[1]), min(l[0], r[0])
return dfs(root)[int(result)]
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.