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) or 1 (True) - these are your boolean literals
  • Non-leaf nodes contain values 2 (OR operation) or 3 (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
2ORRoot: OR Operation3ANDAND Operation1Leaf: True1True0FalseEvaluation Steps:1. Evaluate leaves: 1β†’True, 0β†’False2. AND: True ∧ False = False3. Right leaf: 1β†’True4. OR: False ∨ True = TrueFinal Result: TrueTrue AND False = FalseFalse OR True = True
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

n
2n
βœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h

n
2n
βœ“ 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
Asked in
Meta 25 Amazon 18 Google 15 Microsoft 12
42.0K Views
Medium Frequency
~12 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