Home
DSA Patterns
Depth-First Search
Invert Binary Tree
Invert Binary Tree
Mirror a binary tree by swapping every node's left and right children with a depth-first traversal.
Problem Understanding
Invert Binary Tree: given the root of a binary tree, mirror it — every node's left and right children trade places — and return the root.
Example: [4, 2, 7, 1, 3, 6, 9] becomes [4, 7, 2, 9, 6, 3, 1].
Attempt 1: Rebuild the Tree Level by Level
One way is to read the tree level by level, reverse each level, and build a new tree from the result. It works, but it allocates a whole new tree and has to track where empty children belong. The mirror is a local change: each node only needs its own two child pointers swapped.
The Intuition: Swap, Then Let the Recursion Finish the Job
A tree is mirrored exactly when every node's children are swapped:
- If the node is
null, there is nothing to do — returnnull. - Swap the node's
leftandrightpointers. - Invert the (new) left subtree, then the (new) right subtree.
- Return the node.
Each node is swapped once, before its children, so the whole tree is mirrored in one depth-first pass. This is the DFS pattern in its simplest form: do the work at the node, then hand the same problem to each child.
Interactive Walkthrough
FILLED = CHILDREN ALREADY SWAPPED
CALL
Swapped
0 / 7
Stack depth
1
call stack
invertTree(4)
Next
Swap 4's children: left is now 7, right is now 2
Tree
The tree is redrawn from its links at every step, so each swap is visible as two subtrees trading sides. The calls in progress are outlined from the root down to the running one, swapped nodes fill in, and an empty child shows the null it returns.
