Evaluate Boolean Binary Tree - Problem
You're given a full binary tree that represents a boolean expression ready to be evaluated! This tree has a special structure:
- Leaf nodes contain values
0(False) or1(True) - these are your boolean literals - Non-leaf nodes contain values
2(OR operation) or3(AND operation) - these are your boolean operators
Your mission is to evaluate this boolean expression tree and return the final result.
How evaluation works:
- π Leaf nodes: Simply return their value (0 = False, 1 = True)
- πΏ Non-leaf nodes: Evaluate both children, then apply the boolean operation
Think of it like parsing a mathematical expression, but with boolean logic instead of arithmetic!
Note: A full binary tree means every node has either 0 children (leaf) or exactly 2 children (internal node).
Input & Output
example_1.py β Simple OR Operation
$
Input:
root = [2,1,3,null,null,0,1]
βΊ
Output:
true
π‘ Note:
The tree represents (True OR (False AND True)). First evaluate (False AND True) = False, then (True OR False) = True.
example_2.py β Simple AND Operation
$
Input:
root = [3,1,0]
βΊ
Output:
false
π‘ Note:
The tree represents (True AND False) = False. Both children are leaves, so we directly apply the AND operation.
example_3.py β Single Leaf Node
$
Input:
root = [1]
βΊ
Output:
true
π‘ Note:
Single leaf node with value 1, which represents True.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Node Type
Check if current node is a leaf (0 or 1) or operator (2 or 3)
2
Base Case
If leaf, return corresponding boolean value
3
Recursive Case
Evaluate left and right subtrees recursively
4
Apply Operation
Use AND (3) or OR (2) on the children's results
5
Bubble Up
Return result to parent node in the recursion
Key Takeaway
π― Key Insight: Tree recursion naturally matches the structure of boolean expressions - evaluate children first, then apply the parent's operation
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once where n is number of nodes
β Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h
β Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 1000]
- Node values are 0, 1, 2, or 3 only
- 0 and 1 represent False and True respectively
- 2 and 3 represent OR and AND operations respectively
- The tree is a full binary tree
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code