LeetCode 226: Invert Binary Tree is an Easy binary tree general problem. This Python walkthrough develops a recursive swap solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Binary Tree General |
| Reusable pattern | recursive swap |
| Complexity | O(n) time and O(h) recursion space |
Recognizing the pattern
Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.
For this problem specifically, swap each node’s children and recursively invert the two resulting subtrees. The invariant worth writing beside the code is: Every returned subtree is the mirror image of its original subtree.
Step-by-step algorithm
- Identify the input state consumed by
invertTree(root)and initialize the data required by the recursive swap pattern. - Swap each node’s children and recursively invert the two resulting subtrees.
- After each update, verify the page’s central invariant: Every returned subtree is the mirror image of its original subtree.
- Finish only after the boundary behavior is covered: An empty tree remains empty.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def invertTree(self, root):
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return rootReading the implementation
The main entry point is invertTree(root). The implementation keeps little named state because each operation can be resolved directly from the current input position.
The entry point is recursive: each call reduces the remaining tree, graph, or search state before combining the returned information. In concrete terms, swap each node’s children and recursively invert the two resulting subtrees.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Swap each node’s children and recursively invert the two resulting subtrees. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so every returned subtree is the mirror image of its original subtree.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
inverted=Solution().invertTree(tree([4,2,7,1,3,6,9])); assert inorder(inverted)==[9,7,6,4,3,2,1]Common mistakes and edge cases
- Problem-specific boundary: An empty tree remains empty.
- Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
- Invariant check: after every update, confirm that every returned subtree is the mirror image of its original subtree.
Interview review checklist
- Explain why recursive swap matches the structure of this input.
- State the invariant in one sentence before tracing code: Every returned subtree is the mirror image of its original subtree.
- Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
- Test the boundary explicitly: An empty tree remains empty.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 100. Same Tree · Next: 101. Symmetric Tree