20. Invert Binary Tree
easyAsked at AdyenInvert a binary tree by swapping every node's left and right children.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, invert the tree, and return its root.
Constraints
The number of nodes is in the range [0, 100].-100 <= Node.val <= 100
Examples
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]Approaches
1. Recursive swap
Swap children then recurse.
- Time
- O(n)
- Space
- O(h)
function invert(root) {
if (!root) return null;
[root.left, root.right] = [invert(root.right), invert(root.left)];
return root;
}Tradeoff:
2. Iterative queue
BFS the tree, swapping each node's children.
- Time
- O(n)
- Space
- O(n)
function invertTree(root) {
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:
Adyen-specific tips
Adyen graders care more about the iterative variant — their fraud-signal trees in production are walked iteratively to keep call stacks small.
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 Adyen interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →