Home
DSA Patterns
Depth-First Search
Invert Binary Tree
Invert Binary Tree (LeetCode 226)
Invert Binary Tree (LeetCode 226): 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.
Invert Binary Tree Visualization
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.
Invert Binary Tree Dry Run
Input: [4, 2, 7, 1, 3, 6, 9]
| Call | Swap | Children after |
|---|---|---|
invertTree(4) |
2 ↔ 7 | left 7, right 2 |
invertTree(7) |
6 ↔ 9 | left 9, right 6 |
invertTree(9), invertTree(6) |
leaves: null ↔ null | - |
invertTree(2) |
1 ↔ 3 | left 3, right 1 |
invertTree(3), invertTree(1) |
leaves: null ↔ null | - |
The root is returned; read level by level the tree is now [4, 7, 2, 9, 6, 3, 1].
Invert Binary Tree LeetCode Solution
Pre-order DFS: swap, then recurse.
Invert Binary Tree Code
1var invertTree = function(root) {2 if (root === null) {3 return null;4 }5 [root.left, root.right] = [root.right, root.left];6 invertTree(root.left);7 invertTree(root.right);8 return root;9};
Invert Binary Tree in Python, Java, C++, TypeScript and C
Invert Binary Tree in Python
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return rootInvert Binary Tree in Java
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;
}
}Invert Binary Tree in C++
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) {
return nullptr;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};Invert Binary Tree in TypeScript
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) {
return null;
}
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
}Invert Binary Tree in C
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL) {
return NULL;
}
struct TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}Edge Cases & Common Mistakes
- Empty tree: return
nullimmediately. - One node: its two null children are swapped; nothing visible changes.
- Overwriting before saving:
root.left = root.right; root.right = root.left;loses the original left child: swap through a temporary (or a tuple assignment). - Swapping in-order: swapping between the two recursive calls inverts one subtree twice and leaves the other untouched.
- Very deep, skewed trees: recursion depth equals the height; an iterative BFS with a queue avoids stack overflow.
Summary
Mirror a tree by swapping each node's children and recursing: pre-order or post-order both work, in-order does not. Every node is visited once: O(n) time and O(h) stack space.
More practice: DSA interview questions with answers · patterns cheat sheet
