#2331
Evaluate Boolean Binary Tree
EasyTreeDepth-First SearchBinary TreeDepth-First SearchRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a depth-first search (DFS) approach to evaluate the tree in a single pass. By recursively evaluating each node and applying the boolean operations directly, we avoid unnecessary recalculations, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: If the current node is a leaf, return its value (0 or 1).
- 2Step 2: Recursively evaluate the left and right children.
- 3Step 3: Based on the current node's value, return the result of the boolean operation applied to the evaluations of the children.
solution.py14 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def evaluate_tree(root):
9 if root.val == 0 or root.val == 1:
10 return bool(root.val)
11 left_eval = evaluate_tree(root.left)
12 right_eval = evaluate_tree(root.right)
13 return (left_eval or right_eval) if root.val == 2 else (left_eval and right_eval)
14ℹ
Complexity note: The time complexity is O(n) because we traverse each node exactly once. The space complexity is O(n) due to the recursion stack in the worst case (a skewed tree).
- 1Understanding the structure of the binary tree is crucial for evaluating nodes correctly.
- 2Recognizing leaf nodes and their values helps in simplifying the evaluation process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.