← Back to DSA Animator
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.