Call stack one frame per invertTree call · newest on the right
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode tmp = root.left; root.left = root.right; root.right = tmp; invertTree(root.left); invertTree(root.right); return root;}
- root
- —
- root.left
- —
- root.right
- —
- frames
- 0
- swaps
- 0
Why it works
- A mirror swaps left and right at every level, not just at the root. Swapping the root's children moves two whole subtrees across; each of them still has to be mirrored inside, which is the same problem, one level smaller.
- No copy needed. Building a mirrored copy node by node also works but allocates n new nodes. Swapping pointers in place touches each node once: O(n) time, nothing extra but the call stack.
- The call stack holds the path from the root to the node being worked on, so it grows to the tree's height h: O(log n) when balanced, O(n) for a chain where each node has one child.
- Swap before or after the recursive calls (pre-order or post-order): both give the same mirror, as long as each node is swapped exactly once.
- Pitfall, in-order:
invertTree(root.left), swap,invertTree(root.right)mirrors the old left subtree twice and the old right one never, because after the swaproot.rightis the subtree you already did. - Iterative version: a queue (BFS) or stack (DFS) of nodes; pop one, swap its children, push the non-null ones. Same O(n), and no
StackOverflowErroron very deep trees.