DSA AnimatorDSA animations
Invert Binary Tree LC #226 Easy DFS · Pre-order Swap
Problem

Given the root of a binary tree, invert the tree, and return its root. Inversion means every node's left and right children are swapped — recursively throughout the entire tree.

Example 1
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Explanation: Swap every node's children top-down.
Example 2
Input: root = [2,1,3]
Output: [2,3,1]
Example 3
Input: root = [1]
Output: [1]
Constraints: 0 ≤ nodes ≤ 100  |  −100 ≤ Node.val ≤ 100
Try Examples
Custom:
Approach
DFS Pre-order: Swap First, Then Recurse
At every node: swap left and right children (O(1)), then recurse into the new left and right. Pre-order ensures the swap happens before we recurse into children.
Swap Indicator
Select a step to see swap detail
Binary Tree (Live)
Current
Swapping
Swapped
Done
Variables
Current Node
—
Left Child
—
Right Child
—
Phase
—
Recursion Stack
Stack is empty
Step Logic
Press ▶ Play or Next Step to begin the animation.
✓
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Base case: root == null → return null
2
Swap: tmp=root.left; root.left=root.right; root.right=tmp
3
Recurse left: invertTree(root.left)
4
Recurse right: invertTree(root.right)
5
Return root
Time
O(n)
Space
O(h)
Why Pre-order Works

We swap a node's children before recursing into them. This is safe because the swap is an O(1) pointer exchange — no recursion needed first. After swapping, we recurse into what is now root.left (which was previously root.right) and vice versa. Every node is visited exactly once → O(n) time, O(h) stack space where h is the tree height.

How to solve Invert Binary Tree

LeetCode 226 · Easy · Tree · Pattern: DFS Swap

Why the obvious approach is slow

You might try to rebuild a new tree level by level in reverse order. But the mirror image is just one swap per node, so no new tree is needed.

The key idea

At every node, swap its left and right child. Then invert the left subtree and the right subtree in the same way. A null node needs no work, so it is the base case. The order of the swap and the recursive calls does not matter, as long as every node is swapped exactly once.

Remember

Swap the children, then recurse into both sides. A breadth first search with the same swap works too.

Run the animation above on your own input, or watch the 1:50 video explanation of Invert Binary Tree with a dry run and Java code.

More Tree problems