15% off all plans & roadmaps Use code
See plansInvert Binary Tree
- LeetCode 226
- Easy
- Tree Traversal Patterns (DFS & BFS)
- Recursive Preorder Traversal
Updated
TL;DR: Invert a binary tree by swapping the left and right child of every node. A recursive preorder DFS does it in place in O(n) time and O(h) stack space.
Problem
Given the root of a binary tree, invert the tree and return its root. Inverting means every node's left and right children trade places, all the way down.
Example 1
Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
Example 2
Input: root = [2,1,3] Output: [2,3,1]
Example 3
Input: root = [] Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Constraints that matter
- At most 100 nodes means any O(n) or even O(n^2) method passes, so the interview is about clean tree handling, not speed.
- The node count can be 0, so the root can be null. Every approach must handle that before touching
root.left. - Height is at most 100 in the worst case (a chain), so recursion depth is safe here. In production code with deep trees, prefer an explicit queue or stack.
- Values are in [-100, 100] and never get compared or combined, so only the shape of the tree matters. Values ride along with their nodes.
Hints
Hint 1
This is a tree traversal problem.
Hint 2
Leave the input tree alone and construct a brand new tree.
Solution
Intuition
This is a tree traversal problem. The output depends on every node, so you must visit each one at least once. The open questions are what to do at each visit and in which order.
Picture a mobile hanging from a ceiling, where each bar holds two arms that can be flipped. You walk down from the top, flip each bar, and carry only your current path, which is the call stack.
Look at the definition of a mirror image. A tree is inverted when its root's two children trade places and each of those subtrees is itself inverted. That sentence is recursive, which points at a depth-first search. The same shape of problem appears in Same Tree, Symmetric Tree and Maximum Depth.
The work at one node is tiny: swap two pointers. You can do it before you recurse (preorder) or after (postorder). Both are correct, because swapping a node's children does not change what is inside each child's subtree. Preorder reads most naturally: swap here, then fix the children.
Why it works: after the swap at node x, the old right subtree hangs on the left and the old left subtree hangs on the right. Recursing on both subtrees inverts each one internally. By induction on height, the whole subtree under x is a mirror of the original.
Worked example
Input: root = [5, 3, 8, 2, null, 6, 10, null, null, null, null, 9] Output: [5, 8, 3, 10, 6, null, 2, null, 9] Explanation: Node 5 has left child 3 and right child 8. Node 3 has only a left child 2. Node 8 has children 6 and 10, and node 10 has a left child 9. After inversion, 5 has left child 8 and right child 3. Node 8 has left child 10 and right child 6, and 10 now holds 9 on its right. Node 3 holds 2 on its right.
Approach 1: Brute force: build a mirrored copy
Leave the input tree alone and construct a brand new tree. For each original node, allocate a new node with the same value. Hang the mirrored copy of the original right subtree on its left, and the mirrored copy of the original left subtree on its right.
Many people write this first because it follows the definition word for word and never mutates the input. It is correct, but it pays for a second tree.
Steps
- If
rootis null, return null. - Create a new node with
root.val. - Set the new node's left to the mirrored copy of
root.right. - Set the new node's right to the mirrored copy of
root.left. - Return the new node.
Dry run
Run on the example [5,3,8,2,null,6,10,null,null,null,null,9].
copy(5)makes a new 5, then asks forcopy(8)as its left andcopy(3)as its right.copy(8)makes a new 8 with leftcopy(10)and rightcopy(6).copy(10)makes a new 10 with leftcopy(null)= null and rightcopy(9)= a new leaf 9.copy(6)makes a leaf 6.copy(3)makes a new 3 with leftcopy(null)= null and rightcopy(2)= a new leaf 2.
The returned tree is 5 with children 8 and 3, 8 with children 10 and 6, 10 with right child 9, and 3 with right child 2. Level order is [5,8,3,10,6,null,2,null,9], which matches the expected output. Seven new nodes were allocated.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. Each node triggers exactly one call that does constant work, and every null child triggers one extra constant-time call, so total calls are at most 2n + 1. The new tree holds n nodes, so memory is O(n) for the copy. The O(h) recursion stack is dominated by it.
PythonTested in our runner
from typing import List, Optional
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
node = TreeNode(root.val)
# the mirrored right side becomes the new left side, and vice versa
node.left = self.invertTree(root.right)
node.right = self.invertTree(root.left)
return nodeJavaTested in our runner
import java.util.*;
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode node = new TreeNode(root.val);
// the mirrored right side becomes the new left side, and vice versa
node.left = invertTree(root.right);
node.right = invertTree(root.left);
return node;
}
}C++Tested in our runner
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return nullptr;
}
TreeNode* node = new TreeNode(root->val);
// the mirrored right side becomes the new left side, and vice versa
node->left = invertTree(root->right);
node->right = invertTree(root->left);
return node;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root === null) {
return null;
}
const node = new TreeNode(root.val);
// the mirrored right side becomes the new left side, and vice versa
node.left = invertTree(root.right);
node.right = invertTree(root.left);
return node;
};GoTested in our runner
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
node := &TreeNode{Val: root.Val}
// the mirrored right side becomes the new left side, and vice versa
node.Left = invertTree(root.Right)
node.Right = invertTree(root.Left)
return node
}C#Tested in our runner
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode node = new TreeNode(root.val);
// the mirrored right side becomes the new left side, and vice versa
node.left = invertTree(root.right);
node.right = invertTree(root.left);
return node;
}
}Approach 2: Iterative BFS with a queue
What's slow: the copy allocates n extra nodes, and the problem never asks for a new tree. It asks you to return the root of the inverted tree, so reusing the existing nodes is allowed and cheaper.
The insight that fixes it: a swap at one node does not depend on any other node. Visit every node in any order and swap its two child pointers where it stands. A queue gives a clean level-by-level visit order and needs no recursion.
Steps
- If
rootis null, return null. - Put
rootin a queue. - Pop a node from the front of the queue.
- Swap its
leftandrightpointers. - Push each non-null child onto the queue.
- Repeat until the queue is empty, then return
root.
Dry run
Run on the example. Each row shows the node popped and the queue after its children are pushed.
| Pop | After swap | Queue after pushes |
|---|---|---|
| start | [5] | |
| 5 | left 8, right 3 | [8, 3] |
| 8 | left 10, right 6 | [3, 10, 6] |
| 3 | left null, right 2 | [10, 6, 2] |
| 10 | left null, right 9 | [6, 2, 9] |
| 6 | leaf, no change | [2, 9] |
| 2 | leaf, no change | [9] |
| 9 | leaf, no change | [] |
The queue is empty, and the tree reads [5,8,3,10,6,null,2,null,9] in level order.
Complexity
| Time | O(n) |
|---|---|
| Space | O(w) |
Let n be the node count and w the maximum number of nodes on one level. Each node enters the queue once and leaves once, and each pop does constant work, so time is O(n). The queue holds at most about two adjacent levels at any moment, so extra space is O(w). In the worst case, a full tree, that is O(n), since the last level holds about n/2 nodes.
PythonTested in our runner
from collections import deque
from typing import List, Optional
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
queue = deque([root])
while queue:
node = queue.popleft()
node.left, node.right = node.right, node.left
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return rootJavaTested in our runner
import java.util.*;
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
return root;
}
}C++Tested in our runner
#include <queue>
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return nullptr;
}
std::queue<TreeNode*> queue;
queue.push(root);
while (!queue.empty()) {
TreeNode* node = queue.front();
queue.pop();
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
if (node->left != nullptr) {
queue.push(node->left);
}
if (node->right != nullptr) {
queue.push(node->right);
}
}
return root;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root === null) {
return null;
}
const queue = [root];
let head = 0; // index pointer avoids the cost of shift()
while (head < queue.length) {
const node = queue[head++];
const temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
return root;
};GoTested in our runner
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
queue := []*TreeNode{root}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
node.Left, node.Right = node.Right, node.Left
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
return root
}C#Tested in our runner
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
TreeNode node = queue.Dequeue();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) {
queue.Enqueue(node.left);
}
if (node.right != null) {
queue.Enqueue(node.right);
}
}
return root;
}
}
Solution pattern
Recursive Preorder Traversal
Approach 3: Recursive preorder DFS, swap in placeOptimalRecursive Preorder Traversal
What's slow: the queue can hold a whole level at once, which is about half the nodes in a full tree. You pay that memory only to control visit order, and visit order does not matter here.
The insight that fixes it: let the call stack do the bookkeeping. A depth-first walk keeps only the current root-to-node path, so extra space is the tree height h. At each node, swap the children first (preorder), then recurse into both. The function returns root, so the caller can reattach the subtree and the final return value is the original root.
Steps
- If
rootis null, return null. This is the base case. - Swap
root.leftandroot.rightusing a temp variable or tuple swap. - Recurse on
root.left, which is now the old right child. - Recurse on
root.right, which is now the old left child. - Return
root.
Dry run
Trace on the example. Depth is the recursion depth, and "children after swap" shows left, right.
| Step | Call | Depth | Children after swap | Next |
|---|---|---|---|---|
| 1 | invert(5) | 0 | 8, 3 | go left to 8 |
| 2 | invert(8) | 1 | 10, 6 | go left to 10 |
| 3 | invert(10) | 2 | null, 9 | go left to null |
| 4 | invert(null) | 3 | none | return null |
| 5 | invert(9) | 3 | null, null | both null, return 9 |
| 6 | back in 10 | 2 | done | return 10 |
| 7 | invert(6) | 2 | null, null | return 6 |
| 8 | back in 8 | 1 | done | return 8 |
| 9 | invert(3) | 1 | null, 2 | left null, then 2 |
| 10 | invert(2) | 2 | null, null | return 2 |
| 11 | back in 5 | 0 | done | return 5 |
The final tree has 5 with children 8 and 3, 8 with children 10 and 6, 10 with right child 9, and 3 with right child 2. Level order is [5,8,3,10,6,null,2,null,9], the expected output. Maximum depth reached was 3, so the stack never held more than four frames.
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) |
Let n be the node count and h the tree height. Each node is entered once and does one swap, and each null child costs one constant-time call. That gives at most 2n + 1 calls, so time is O(n). The stack holds one frame per level on the current path, so space is O(h): about log n for a balanced tree and n for a chain. No new nodes are created.
PythonTested in our runner
from typing import List, Optional
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
# preorder step: swap before descending
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return rootJavaTested in our runner
import java.util.*;
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
// preorder step: swap before descending
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}C++Tested in our runner
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return nullptr;
}
// preorder step: swap before descending
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root === null) {
return null;
}
// preorder step: swap before descending
const temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
};GoTested in our runner
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
// preorder step: swap before descending
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}C#Tested in our runner
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
// preorder step: swap before descending
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}Common mistakes
- Dereferencing before the null check, such as writing
root.leftfirst whenrootcan be null. An empty tree is a valid input, so testif root is None: return Noneon the first line. - Writing
root.left = invert(root.right)and thenroot.right = invert(root.left). The second line reads the left pointer you overwrote, so both sides end up with the same subtree. Save the old left in a temp variable, or use a tuple swap, and only then recurse. - Swapping only at the root. Doing
root.left, root.right = root.right, root.leftonce and returning leaves every deeper subtree in its original orientation. Recurse into both children. - Forgetting
return rootat the end. The function signature promises the root back, and a missing return givesNoneornullto the caller, which looks like an empty answer. - Swapping node values instead of pointers. Exchanging
left.valwithright.valmoves only the two children's values and leaves their subtrees where they were. Swap the child references. - In the BFS version, pushing children before the swap, or pushing null children. Null pushes crash on the next pop when you read
node.left. Swap first, then push only non-null children.
Edge cases
- Empty tree
[]: return null (orNone) immediately, with no crash. - Single node
[1]: the swap exchanges two nulls and the tree is unchanged. - Two nodes
[1,2]: the left child 2 moves to the right, giving[1,null,2]. - Left-leaning chain with 100 nodes: depth is 100, still safe for recursion, and it becomes a right-leaning chain.
- Duplicate or negative values such as
[-1,-1,-1]: values are never compared, so the result is the same shape with the same values. - Tree where only one side exists below a node, like node 10 in the example with only a left child 9: the child must end up on the right, and the null must move to the left.
Follow-ups interviewers ask
- How would you do this without recursion?
- Use an explicit queue for BFS or an explicit stack for DFS. Pop a node, swap its children, push the non-null children, and repeat until empty. Time stays O(n). The stack version uses O(h) extra space for a skewed tree walk and the queue version uses O(width). Neither can overflow the call stack.
- What if the tree is far deeper than 100 levels and recursion might overflow?
- Switch to the iterative version. A chain of a million nodes would blow the default recursion limit in Python and the call stack in most languages, while an explicit queue or stack lives on the heap. Both need O(n) space in the worst case, but only the iterative one is safe against stack overflow.
- What if you must not modify the input tree?
- Build a mirrored copy, which is the brute-force approach. Each call allocates a node with the same value and attaches the mirrored right copy on the left and the mirrored left copy on the right. It costs O(n) time and O(n) extra memory for the new nodes, and the original stays intact.
Invert Binary Tree FAQ
What is the time complexity of Invert Binary Tree?
O(n), where n is the number of nodes. Every node is visited once and the swap is constant work. No approach can beat this, because the output depends on every node.
Why use DFS for Invert Binary Tree?
The problem is recursive by definition: a tree is inverted when its children are swapped and both subtrees are inverted. A DFS follows that definition directly in about five lines and keeps only the current path in memory, so extra space is O(h). BFS works equally well but needs a queue.
Can Invert Binary Tree be solved in O(1) extra space?
Not with plain recursion or a queue. Recursion uses O(h) stack, and BFS uses O(width) queue space. Only a threaded traversal such as Morris traversal avoids that extra memory. It is much harder to write correctly, so interviews accept O(h) as the optimal answer here.
What is the space complexity of the recursive solution?
O(h), where h is the tree height, because the call stack holds one frame per level on the current path. For a balanced tree that is about log n. For a chain-shaped tree it is n. The tree itself is modified in place, so no extra nodes are allocated.
Does it matter whether I swap before or after the recursive calls?
No. Preorder (swap then recurse) and postorder (recurse then swap) give the same tree. Swapping a node's children does not alter what is inside either child's subtree, so the order of the two steps never changes the result. Keep the temp variable so you do not overwrite a pointer before reading it.
How do I write Invert Binary Tree in Python?
Return None for a null node, then run root.left, root.right = root.right, root.left, recurse on both children and return root. Python's tuple assignment evaluates the right side first, so the swap needs no temp variable. The recursion depth is at most 100 under the constraints, well under Python's default limit.
Asked at
See which companies ask this — Pro
Related problems
- Same Tree · same technique: Recursive Preorder Traversal
- Binary Tree Preorder Traversal · same technique: Recursive Preorder Traversal
- Symmetric Tree · same technique: Recursive Preorder Traversal
- Binary Tree Paths · same technique: Recursive Preorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal · same technique: Recursive Preorder Traversal
- Balanced Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Diameter of Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Maximum Depth of Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Subtree of Another Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)