File: evaluate-boolean-binary-tree/solution.py

Date: 2026-06-06

Time: 16:29

Purpose

This file solves LeetCode 2331 — Evaluate Boolean Binary Tree. It defines the tree node structure, the recursive evaluator, a test helper for building trees from level-order lists, and a full test suite — all in a single self-contained module.

Key Components

TreeNode (class)

Standard binary tree node with val, left, right. Used both as the input structure for the evaluator and by the test helper. The val field carries dual semantics: for leaf nodes it's 0 (False) or 1 (True); for internal nodes it's 2 (OR) or 3 (AND).

evalTree(root) -> bool

The core algorithm. Recursively evaluates a full binary tree — every node is either a leaf (both children None) or has exactly two children. The recursion bottoms out when root.left is None, returning bool(root.val). For internal nodes, it evaluates both subtrees then applies OR (val 2) or AND (val 3).

buildtree(vals) -> Optional[TreeNode]

Test utility that constructs a TreeNode tree from a level-order list (BFS order), where None entries represent absent children. Uses a queue-based approach identical to LeetCode's own serialization format.

TestEvalTree (unittest.TestCase)

Nine test cases covering: both LeetCode examples, single-node trees, all four boolean combinations for AND/OR, nested multi-level trees, and a chained AND structure.

Patterns

Dependencies

Imports: annotations (PEP 604 union syntax), unittest, typing.Optional. No external libraries.

Imported by: The testsolution.py file in this same directory imports from it. The massive "Imported By" list in the prompt is misleading — those are other problems' test files that share the same testsolution.py naming pattern; they don't actually import *this* file.

Flow

1. Caller passes a TreeNode root to evalTree.

2. If the node is a leaf (left is None), return bool(val) — converts 0 → False, 1 → True.

3. Otherwise, recurse into left and right subtrees.

4. Apply the operator: val == 2left or right; anything else (implicitly val == 3) → left and right.

5. Python's or/and operators short-circuit, but since both subtrees are already evaluated before the operator check, no short-circuit optimization actually occurs.

Invariants

Error Handling

None. The function trusts its input completely, consistent with LeetCode's problem constraints. No validation of val ranges, tree structure, or null root.

Topics to Explore

Beliefs