Evaluate Boolean Binary Tree (LeetCode 2331): Solution and Explanation

Easy
Tree
Depth First Search
Binary Tree

Evaluate a full binary tree whose leaves are 0/1 and whose inner nodes are OR (2) or AND (3) gates. A post-order recursion computes each gate after both of its inputs.

Intuition

The tree is a tiny logic circuit. Leaves are the inputs and every inner node is a gate with exactly two inputs, because the tree is full.

A gate cannot produce its output until both inputs are known, so values have to flow from the leaves upward. That is exactly what a post-order traversal does.

Because every inner node has two children, checking only whether the left child exists is enough to tell a leaf from a gate.

Approach: Post-order recursion

  1. If root.left is missing, the node is a leaf: return root.val == 1.
  2. Recursively evaluate the left subtree and the right subtree.
  3. If root.val == 2 return left or right, otherwise return left and right.

Step-by-step example

root = [2,1,3,null,null,0,1]
  1. The root is an OR gate. Evaluate its left child first: leaf 1, which is True.
  2. Evaluate its right child, an AND gate. Its inputs are leaf 0 (False) and leaf 1 (True).
  3. The AND gate gives False AND True = False.
  4. Back at the root, True OR False = True, so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def evaluateTree(self, root: Optional[TreeNode]) -> bool:
3        if not root.left:
4            return root.val == 1
5        left = self.evaluateTree(root.left)
6        right = self.evaluateTree(root.right)
7        if root.val == 2:
8            return left or right
9        return left and right
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is evaluated exactly once.

Space

O(h)

The recursion stack is as deep as the tree height h, which is at most n.

Other approaches

Short-circuit evaluation (time O(n), space O(h))

Skip the right subtree when the left result already decides the gate (True for OR, False for AND). Same worst case, often fewer visits.

Iterative post-order with a stack (time O(n), space O(n))

Simulate the recursion with an explicit stack and a value map. Useful in languages with small call stacks.

Common mistakes

  • Treating values 2 and 3 as truthy numbers instead of as operators.
  • Checking root.val before knowing whether the node is a leaf. A leaf is identified by its missing children, not by its value.
  • Returning the integer value of a leaf rather than a boolean in strongly typed languages.

Frequently asked questions

Why is checking only the left child enough?

The tree is full, so a node has either zero or two children. If the left child is missing, the right one is too.

Does short-circuiting change the result?

No. OR with a True input is True and AND with a False input is False regardless of the other input, so skipping it only saves work.