LeetCode Β· #226
Invert Binary Tree Solution
Given the root of a binary tree, invert it β swap every left and right child β and return the root.
01
Section One Β· Problem
Problem Statement
Given the root of a binary tree, invert the tree (mirror it) and return its root. Every left child becomes the right child and vice versa, at every level.
Example
Input: 4
/ \
2 7
/ \ / \
1 3 6 9
Output: 4
/ \
7 2
/ \ / \
9 6 3 1
Constraints
β’ 0 β€ number of nodes β€ 100 β’ -100 β€ Node.val β€ 100
02
Section Two Β· Approach 1
Iterative BFS β O(n)
Use a queue. For each node, swap its left and right children, then enqueue both. Level-by-level inversion.
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(n) β queue holds up to n/2 nodes |
03
Section Three Β· Approach 2
Recursive DFS β O(n)
At each node: swap left and right, then recursively invert both subtrees. Base case: null node returns null. The recursion naturally handles every level.
π‘ Mental model: Imagine mirroring a family tree β at every person, swap their left and right children. Do this top-down (or bottom-up β order doesn't matter because the swap is independent at each node).
Algorithm
- Base case: If root is null, return null.
- Swap:
temp = root.left; root.left = root.right; root.right = temp; - Recurse:
invertTree(root.left); invertTree(root.right); - Return: root.
π― Pattern recognition:
- "Transform every node" = visit all nodes + do constant work each. This is the simplest tree recursion pattern.
- It appears in LC 226, LC 101 (Symmetric Tree as a variation), and any problem that modifies tree structure.
04
Section Four Β· Trace
Visual Walkthrough
Recursive inversion β swap at each node
05
Section Five Β· Implementation
Code β Java & Python
Java β Recursive
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
Python β Recursive
class Solution:
def invertTree(self, root):
if not root: return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
06
Section Six Β· Analysis
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Recursive DFS | O(n) | O(h) | Call stack = tree height. O(log n) balanced, O(n) skewed. |
| Iterative BFS | O(n) | O(n) | Queue up to n/2 nodes at widest level. |
07
Section Seven Β· Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Empty tree | null | Base case β return null. |
| Single node | [1] | Swap nullβnull β unchanged. |
| Skewed (linked list) | 1β2β3 | Swaps at each level flip leftβright. Stack depth = n. |
β Common Mistake: Inverting only the first level (swapping root's children but not recursing). The swap must happen at every node, not just the root.