File: invert-binary-tree/solution.py

Date: 2026-06-06

Time: 17:08

invert-binary-tree/solution.py

Purpose

This file is a self-contained solution to LeetCode #226 — Invert Binary Tree. It owns the complete lifecycle: tree data structure, the inversion algorithm, serialization/deserialization helpers for testing, and the test suite itself. Within the project, it follows the standard pattern where each problem directory contains a solution.py that doubles as both implementation and test module.

Key Components

TreeNode (line 7–10) — Standard binary tree node with val, left, right. Uses from _future_ import annotations to allow the forward-reference TreeNode | None in the type hints without quoting.

invert_tree(root) (line 13–23) — The core algorithm. Takes a root node (or None) and returns the root of the inverted tree. The inversion is done in-place — it mutates the existing tree rather than building a new one.

The key line is:


root.left, root.right = invert_tree(root.right), invert_tree(root.left)

This is a simultaneous swap via tuple unpacking. Both recursive calls execute before either assignment lands, so there's no risk of clobbering root.left before the right-side recursion reads it.

treetolist(root) (line 26–39) — BFS level-order serialization. Converts a tree into LeetCode's standard list format ([4, 7, 2, 9, 6, 3, 1]), stripping trailing Nones. Used exclusively for test assertions.

listtotree(vals) (line 42–57) — The inverse: builds a TreeNode tree from a level-order list. Drives test setup. Handles None entries as absent children.

TestInvertTree (line 60–78) — Six test cases covering: a full binary tree, a small tree, empty input, single node, left-skewed, and right-skewed trees.

Patterns

Dependencies

Imports: Only _future_.annotations (for PEP 604 union syntax on older Pythons) and unittest (stdlib). No external libraries.

Imported by: The "Imported By" list in the prompt is misleading — it lists hundreds of test files across other problems. These almost certainly import unittest or share a test runner, not this specific file. The actual invert-binary-tree/testsolution.py is the real consumer, likely importing inverttree, TreeNode, listtotree, and treetolist.

Flow

1. listtotree builds a tree from a level-order list using BFS (queue-based construction).

2. invert_tree recurses depth-first to the leaves, then swaps children on the way back up.

3. treetolist serializes the result via BFS for comparison against the expected list.

The recursion depth is O(h) where h is the tree height — O(log n) for balanced trees, O(n) worst case for skewed trees.

Invariants

Error Handling

There is none beyond the None base case. The code assumes well-formed input: vals[0] is never None in listtotree, tree nodes always have integer values, and the list length is consistent with a valid binary tree. This is appropriate for a LeetCode solution where inputs are guaranteed valid.

Topics to Explore

Beliefs