File: leaf-similar-trees/solution.py

Date: 2026-06-06

Time: 17:20

leaf-similar-trees/solution.py

Purpose

This file solves LeetCode 872 - Leaf-Similar Trees. It determines whether two binary trees have the same leaf value sequence — the left-to-right ordering of values at leaf nodes. The file is self-contained: it defines the tree data structure, the solution, a tree builder utility, and unit tests.

Key Components

TreeNode (line 9-12) — Standard binary tree node with val, left, right. This is the canonical LeetCode tree node definition, used across many solutions in this repo.

Solution.leafSimilar (line 16-29) — The core algorithm. Takes two tree roots, extracts the leaf sequence from each, and compares them for equality.

get_leaves (line 25-29) — Nested helper that recursively collects leaf values via DFS. The base cases are:

This guarantees left-to-right ordering because left subtree is always visited before right.

build_tree (line 32-46) — Constructs a TreeNode tree from a level-order list (LeetCode's standard serialization format where None represents absent nodes). Uses BFS with a queue to assign children.

TestLeafSimilar (line 49-75) — Six test cases covering: the two LeetCode examples, single-node trees (equal and unequal), trees with different structures but identical leaf sequences, and mismatched leaf counts.

Patterns

Dependencies

Imports: annotations (for forward-reference type hints in TreeNode), unittest, typing.Optional.

Imported by: The "Imported By" list is misleadingly large — it reflects testsolution.py files across the repo that likely import a shared test runner or tree utility, not this specific file. The actual leaf-similar-trees/testsolution.py imports from this module.

Flow

1. Caller passes two tree roots to leafSimilar.

2. get_leaves performs a depth-first traversal of each tree, collecting values only at leaf nodes (nodes with no children).

3. The two resulting lists are compared with ==.

For a tree like [3, 5, 1, 6, 2, 9, 8, None, None, 7, 4], get_leaves produces [6, 7, 4, 9, 8] — the leaves read left-to-right.

Invariants

Error Handling

None. The code trusts its inputs — no validation on tree structure, no exception handling. This is standard for LeetCode solutions where inputs are guaranteed well-formed.

Performance Note

get_leaves builds intermediate lists via concatenation (+), which is O(n) per concatenation. For a balanced tree of n nodes this gives O(n log n) total work. A production version would use a single list with .append() or a generator to achieve O(n). For LeetCode's constraints (up to 200 nodes), this doesn't matter.

Beliefs