10. Invert Binary Tree
easyAsked at Byju'sMirror a binary tree by swapping left and right children at every node.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, invert the tree by swapping left and right children at every node, and return the root. Both iterative (BFS/queue) and recursive solutions are acceptable. The tree may contain up to one hundred nodes with values between negative one hundred and one hundred.
Constraints
0 <= nodes <= 100-100 <= Node.val <= 100
Examples
Example 1
root = [4,2,7,1,3,6,9][4,7,2,9,6,3,1]Example 2
root = [2,1,3][2,3,1]Approaches
1. Iterative BFS swap
Queue every node, swap its children, push children onto the queue.
- Time
- O(n)
- Space
- O(n)
if(!root) return null;
const q=[root];
while(q.length){
const n=q.shift();
[n.left,n.right]=[n.right,n.left];
if(n.left)q.push(n.left);
if(n.right)q.push(n.right);
}
return root;Tradeoff:
2. Recursive swap
Swap children at each node then recurse on both subtrees. Mirrors the tree in a clean post-order traversal.
- Time
- O(n)
- Space
- O(h)
function invertTree(root) {
if (!root) return null;
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)];
return root;
}Tradeoff:
Byju's-specific tips
Byju's teaching-centric culture rewards candidates who literally draw the mirror flip before coding, so reach for a whiteboard or share-screen sketch early.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Invert Binary Tree and other Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →