Evaluate Boolean Binary Tree

You are given the `root` of a **full binary tree** (every node has 0 or 2 children). - Leaf nodes hold `0` (False) or `1` (True). - Non-leaf nodes hold `2` (boolean OR) or `3` (boolean AND). A leaf evaluates to its own value. A non-leaf node evaluates both children and applies its operation to the two results. Return the boolean result of evaluating the root.

30:00

Evaluate Boolean Binary Tree
easy
Free written solution
Topics
Companies

You are given the root of a full binary tree (every node has 0 or 2 children).

  • Leaf nodes hold 0 (False) or 1 (True).
  • Non-leaf nodes hold 2 (boolean OR) or 3 (boolean AND).

A leaf evaluates to its own value. A non-leaf node evaluates both children and applies its operation to the two results. Return the boolean result of evaluating the root.

Example 1:
Input: {"root":[2,1,3,null,null,0,1]}
Output: true
Constraints:
  • The number of nodes in the tree is in the range [1,1000][1, 1000].

  • 0≤0 \le Node.val ≤3\le 3

  • Every node has either 0 or 2 children.

  • Leaf nodes have a value of 0 or 1.

  • Non-leaf nodes have a value of 2 or 3.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[2,1,3,null,null,0,1]}

Read the tree as a circuit: leaves are inputs (0 = False, 1 = True), 2 is an OR gate and 3 is an AND gate. A gate needs both inputs first, so evaluate bottom-up. 2 gates to evaluate.

OR1AND01

call stack

(empty)
settled 0/5
1 / True
0 / False
OR gate (2)
AND gate (3)
on the call stack
Variables
VariableValue
nodes5
gates2
DepthFunction Call
Stack empty
0/10