Invert Binary Tree
Easy · Trees
Jump to codeSwap the left and right children at every node of a binary tree and return its root. An empty tree stays empty.
Examples
Example 1
root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2
root = [2,1,3]
Output: [2,3,1]
Constraints
- 0 <= The number of nodes in the tree <= 100
- -100 <= Node.val <= 100
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Need a hint?
The same operation applies independently to every subtree.
Asked in real interviews
Candidates reported versions of Invert Binary Tree from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
For a non-null node, swap its children and recursively invert both. The base case returns immediately for null. A queue or stack can perform the same traversal iteratively when recursion depth is a concern.
Complexity
O(n) time and O(h) recursive stack space for height h.
Python reference solution
def invertTree(root):
if root:
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
JavaScript solution
function invertTree(root) {
if (root) {
const left = invertTree(root.right);
root.right = invertTree(root.left);
root.left = left;
}
return root;
}
Java solution
import java.util.*;
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root != null) {
TreeNode left = invertTree(root.right);
root.right = invertTree(root.left);
root.left = left;
}
return root;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root) {
TreeNode* left = invertTree(root->right);
root->right = invertTree(root->left);
root->left = left;
}
return root;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
4,
2,
7,
1,
3,
6,
9
]
][ 4, 7, 2, 9, 6, 3, 1 ]
[
[
2,
1,
3
]
][ 2, 3, 1 ]
[ [] ]
[]
[
[
1
]
][ 1 ]
[
[
1,
2,
3,
4,
5,
6,
7
]
][ 1, 3, 2, 7, 6, 5, 4 ]
Drafts are saved per language in this browser when storage is available.