Invert Binary Tree solution explained
To invert a binary tree, visit every node and swap its left and right children; once every node has been swapped, the whole tree is its own mirror image. A recursive version does this in a few lines, and a queue or stack version does the same without recursion. Either way the time is O(n), because each node is handled once.
By Evin JohnPublished 5 min read
What the problem asks
You get the root of a binary tree. Rearrange the tree so that it becomes its mirror image: for every node, what used to be its left subtree is now its right subtree, and the other way around. Values stay on their nodes; only the child links change. Return the root, which is the same node as before.
| Before | After |
|---|---|
| 5 / 3, 9 / 1, -, 7, 11 | 5 / 9, 3 / 11, 7, -, 1 |
| 2 / 1, - | 2 / -, 1 |
| 6 | 6 |
| empty | empty |
Look at the first row closely. The 1 that hung to the left of 3 now hangs to the right of 3, and 3 itself moved to the right of the root. Swapping only the root's children is not enough; every level flips.
Why it gets asked
It is short enough for a warm-up yet tells the interviewer whether you can reason about trees recursively and whether you know at least one iterative traversal. It also surfaces a common bug: overwriting one child before you have saved it. Strong candidates also point out that any traversal order works, since each node's swap is independent of the others.
Follow-ups
- Check whether a tree is symmetric. Compare the left subtree with a mirrored right subtree, without changing anything.
- Return a mirrored copy and keep the original. Build new nodes instead of swapping in place.
- Check whether two trees are mirrors of each other. Recurse on (left of one, right of the other) pairs.
- Do it without recursion. Use a queue or a stack, as below.
A wasteful first attempt
One roundabout approach collects each level's values with a breadth-first walk, reverses each level, and rebuilds a tree from the reversed levels. It works for complete trees but gets awkward with missing children, needs O(n) extra memory and builds new nodes. It is mainly useful for showing why swapping links in place is the better idea.
Recursive inversion
An empty tree is already inverted. For any other node, invert its right subtree and its left subtree, then hang the inverted right one on the left and the inverted left one on the right. In Python, a single tuple assignment does both calls before either child pointer is overwritten, so nothing gets lost.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree(root):
if root is None:
return None
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return rootIterative inversion
Keep a collection of nodes still to process. Take one out, swap its two children, and put any non-empty children in. A queue gives a level-by-level order; a stack gives a depth-first order. Both visit every node once, and neither touches the language's call stack, so very deep trees are safe.
from collections import deque
def invert_tree_iterative(root):
queue = deque([root] if root else [])
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 rootclass TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function invertTree(root) {
const stack = root === null ? [] : [root];
while (stack.length > 0) {
const node = stack.pop();
[node.left, node.right] = [node.right, node.left];
if (node.left !== null) stack.push(node.left);
if (node.right !== null) stack.push(node.right);
}
return root;
}Running any of these twice returns the original tree, which makes a handy self-check when you test by hand: invert, invert again, compare.
Cost of each approach
| Approach | Time | Extra memory |
|---|---|---|
| Reverse each level and rebuild | O(n) | O(n) for levels and new nodes |
| Recursive swap | O(n) | O(h) call stack |
| Queue-based swap | O(n) | O(w) |
| Stack-based swap | O(n) | O(h) |
Trees to test
- An empty tree and a single node.
- A node with only a left child, which should end up with only a right child.
- An uneven tree, such as the first example, to confirm deeper levels flip too.
- A long chain, for stack depth in the recursive version.
Mistakes to avoid
- Writing root.left = invert(root.right) and then root.right = invert(root.left), where root.left has already been replaced.
- Swapping only at the root.
- Forgetting to return the root, or returning a child instead.
- Pushing empty children onto the stack and then crashing when swapping on nothing.
How to explain it out loud
Fictional example
- Candidate
- A mirror image means left and right swap at every node, not just the root. So I visit each node once and swap its children.
- Candidate
- Recursively, I invert both subtrees and attach them crossed over. I compute both before assigning, so I never lose a child.
- Candidate
- It is linear time. Memory is the height for recursion; if the tree might be very deep, I would use a stack or queue instead, and the order of visits does not matter.
Where to go next
Maximum Depth of Binary Tree is the same recursive shape, combining child results instead of swapping them. Binary Tree Level Order Traversal uses the queue from the iterative version to return each level.
Natively while you practice
Mirroring is easy to get wrong on paper, so check your plan against a second opinion. Natively on Mac or Windows can read the tree problem from a screenshot during practice and outline the recursive swap and an iterative version, which you can line up against what you wrote. When you rehearse out loud, the transcript shows whether you mentioned the overwrite trap before writing the code. Read about the AI interview assistant.
Questions people ask
How do you invert a binary tree?
Visit every node and swap its left and right children. Recursively, invert both subtrees and attach them crossed over; iteratively, use a queue or stack and swap each node you take out.
What is the time complexity of inverting a binary tree?
O(n), because each node is visited once. Extra memory is O(h) for recursion or a stack and O(w) for a queue, where w is the widest level.
Does the traversal order matter when inverting a tree?
No. Each swap only touches one node's two child links, so preorder, postorder or level order all produce the same mirrored tree.
How do you invert a tree without recursion?
Put the root in a queue or stack, then repeatedly take a node, swap its children and add the non-empty children, until the collection is empty.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
