Scrivio Interview library
TreesTrees and binary search treesReported 24 times · 16 min read · updated 14 November 2026

Convert a binary tree into its mirror image.

1What the mirror image of a tree means

Think of a family tree drawn on a sheet of paper, with the grandparents at the top and the children spreading out below. Hold the sheet up to a mirror. In the reflection the top stays at the top, but everything that was on the left is now on the right, and the other way round, at every level of the drawing. The eldest cousin, once at the far left, is now at the far right. That reflection is exactly what this question asks for.

Let us name the parts one at a time. A binary tree is made of nodes, and each node holds a value and has at most two children, a left child and a right child. The node at the top is the root. A node with no children is a leaf. The mirror image of a binary tree is the tree in which, at every node, the left child and the right child have changed places.

Our example has root 4 with children 2 and 7; 2 has children 1 and 3, and 7 has children 6 and 9. A handy way to write a tree in one line is its level order, the values read row by row from left to right, which gives 4, 2, 7, 1, 3, 6, 9. In the mirror, the second row reads 7, 2 and the third row reads 9, 6, 3, 1, so the level order becomes 4, 7, 2, 9, 6, 3, 1.

Step throughThe example tree and its mirror

Frame 1 is the tree we are given. Frame 2 is the tree we must turn it into, using the same seven nodes.

  1. 4271369
    level order
    4, 2, 7, 1, 3, 6, 9

    1The tree we are given has root 4, children 2 and 7, and leaves 1, 3, 6 and 9. Read level by level, it is 4, 2, 7, 1, 3, 6, 9.

  2. 4729631
    level order
    4, 7, 2, 9, 6, 3, 1

    2The mirror is the same drawing seen in a looking glass. Every left and right have changed places, so it reads 4, 7, 2, 9, 6, 3, 1.

What to assume

May we change the tree in place, or must the original survive?
We assume we may change it, and we return its root.
Can the tree be empty?
Yes, and its mirror is also empty.
How deep can it be?
Possibly very deep. The main solution is written for trees of ordinary depth, and a second version handles a very long chain.

Let us do it by hand on paper. Draw the tree. At 4, swap its two arms, so 7 is on the left and 2 on the right, each carrying its own children along. At 7, swap again, so 9 is on its left and 6 on its right. At 2, swap, so 3 is on its left and 1 on its right. The leaves have no children to swap. Three swaps and we are done. That is the whole job, and it is much smaller than the word mirror makes it sound.

A careful candidate asks a few questions first. May we change the tree in place, or must the original survive? We assume we may change it, and we return its root. Can the tree be empty? Yes, and its mirror is also empty. How deep can it be? Possibly very deep, so we will also show a version that avoids recursion.

2How to spot the tree recursion pattern

When a beginner first reads this question, the first thought is often to work row by row, because that is how we read the tree. Reverse the second row, reverse the third row, and so on. It is not a bad picture, but it is hard to turn into code, because the rows are not stored anywhere; the tree only knows each node's two children. The question is what each single node has to do.

Let us take the clues one at a time. The first clue is the phrase binary tree. In a binary tree every node is the root of a smaller tree, its subtree, made of itself and everything below it. Many tree questions become simple once we ask what a node must do and trust the same method to handle the subtrees.

The second clue is the word mirror, and how it behaves on a subtree. The mirror of the whole tree is the root, with the mirror of its right subtree hung on the left and the mirror of its left subtree hung on the right. The answer for a tree is built from the answers for its two subtrees, the same problem only smaller.

The third clue is quieter. The work at each node, swapping its two children, does not depend on any other node. It needs no value from above and no result from below. So any walk that reaches every node exactly once and swaps its children will do.

These clues point to the trees family, and to the technique of tree recursion. Recursion means a method that calls itself on a smaller piece of the same problem, here on a node's children. Every recursion needs a base case, a piece so small that the answer is immediate, and here it is the empty tree, null, whose mirror is itself. The rule to carry to new problems is this: when the answer for a tree can be described from the answers for its left and right subtrees, write a recursive method that follows that description, with null as the base case.

Some patterns look similar but need care. A breadth-first walk with a queue, visiting the tree row by row, also works here, because of the third clue, and we include it. The in-order walk, which handles the left subtree, then the node, then the right subtree, looks just as natural but gives a wrong answer, and we will watch exactly why.

3The honest first attempt, building a mirrored copy

A natural first solution leaves the original alone and builds a brand new tree. For each node we make a new node with the same value, whose left child is the mirrored copy of the old right subtree and whose right child is the mirrored copy of the old left subtree. It follows the second clue word for word, which is a good sign, and it is our brute force.

Java
static Node mirrorCopy(Node node) {
if (node == null) return null; // the mirror of nothing is nothing
return new Node(node.val,
mirrorCopy(node.right), // the new left side is the mirrored old right side
mirrorCopy(node.left)); // the new right side is the mirrored old left side
}

Let us run it by hand on our tree. mirrorCopy(4) makes a new 4. Its left child is mirrorCopy(7), which makes a new 7 whose left is a new 9 and whose right is a new 6. Its right child is mirrorCopy(2), which makes a new 2 with a new 3 on its left and a new 1 on its right. Read row by row, the new tree is 4, 7, 2, 9, 6, 3, 1, as our traced run confirms.

Let us count its cost. It makes 7 new nodes for 7 old ones, and each node is visited once, so the time is O(n), read as order n, growing in step with the number of nodes. The extra space is O(n) for the new nodes, plus the waiting recursive calls, one per level of the path being explored.

This is the right answer when the original tree must not change. But when we may change it, where is the waste? Look at any new node. Its value is copied from an old node that already holds exactly that value. The only thing wrong with the old node is the position of its two child references. We built seven new nodes just to change fourteen child references.

4Getting to the in-place swap, one observation at a time

The waste tells us what to do instead. Keep every node where it is and simply swap its two child references. So at each node we exchange left and right, and then we do the same for the two children, so that the swapping reaches every level.

Let us take it slowly at the root. Before the swap, 4 has 2 on its left and 7 on its right. After the swap, 7 is on the left and 2 on the right, and each has carried its whole subtree along, still in its old order. That is half the job. The other half is to mirror inside those two subtrees, and that is the same problem on smaller trees, so we call the same method on each child.

Now the question a beginner asks. Why do we need the variable saved? Why not write node.left = node.right and then node.right = node.left? Let us try it at the root and see. The first line makes left point to 7. The second line copies left into right, but left is now 7, so right becomes 7 as well. Both arms now hold the 7 subtree, and nothing refers to 2 any more, so 2, 1 and 3 are lost. It is the same reason any swap needs a spare place: we keep the old left child in saved before overwriting it.

Does it matter whether we swap before visiting the children or after? Swapping first, as our code does, and swapping last both work, because each node's children are swapped exactly once either way. What does not work is swapping in the middle, the in-order shape, and the picture shows why: the left subtree is mirrored, the swap moves it to the right, and then the method mirrors the right child, which is that same subtree again. One side is mirrored twice, which undoes it, and the other side is never touched. This is the mistake that tempts people who remember in-order as the usual tree walk.

Step throughThe in-order mistake: mirror left, swap, then mirror right

This wrong version recurses into the left child, swaps the node's children, and then recurses into the right child.

  1. 4node271369
    step
    mirror left first

    1At the root, the wrong version first mirrors the left subtree, the one under 2.

  2. 42node73169
    step
    2's subtree mirrored

    2The subtree under 2 is mirrored correctly, so 2 now has 3 on its left and 1 on its right.

  3. 4node726931
    step
    swap at 4

    3Back at 4, it swaps the children. The already mirrored 2 moves to the right, and the untouched 7 moves to the left.

  4. 472node6913
    step
    2 mirrored twice

    4Now it mirrors the right child, but the right child is 2 again. 2 is mirrored a second time, which puts 1 and 3 back where they began.

  5. 4726913
    we got
    4, 7, 2, 6, 9, 1, 3
    we wanted
    4, 7, 2, 9, 6, 3, 1

    5The result reads 4, 7, 2, 6, 9, 1, 3. The subtree under 7 was never mirrored and the one under 2 was mirrored twice, so it is wrong.

Why is the swap-first version correct? Think of it the way the recursion does. Assume, for a moment, that mirror already works on any smaller tree. At a node, we swap its children, so the right subtree is now on the left and the left one on the right. Then we mirror each of them, which by our assumption works. That is exactly the description of a mirror from the second clue. And the smallest tree, null, is handled by returning at once, so the assumption holds from the bottom up.

5Watching the children swap, node by node

The picture runs mirror on our tree. The highlighted node is the one the method is working on; nodes already finished are marked as done. The panel shows how many swaps have happened and the tree's level order after each step.

Watch the order of visits. The method swaps at a node first, then goes into its new left child completely, and only then into its new right child. Because of the swap, the new left child of 4 is 7, so the 7 side is handled before the 2 side, even though 2 was drawn on the left at the start.

Step throughSwapping children node by node on the example tree

The highlighted node is the one mirror is working on. Its children are swapped first, then its two subtrees are mirrored.

  1. 4node271369
    calls so far
    1
    swaps so far
    0

    1We call mirror on the root, 4. Nothing has changed yet, and every node still has its children in the original order.

  2. 4node726913
    node
    4
    swaps so far
    1
    level order
    4, 7, 2, 6, 9, 1, 3

    2mirror(4) saves 4's left child, 2, then sets left to 7 and right to the saved 2. The two whole subtrees have changed sides, each still in its old order.

  3. 47node29613
    node
    7
    swaps so far
    2
    level order
    4, 7, 2, 9, 6, 1, 3

    3Next, mirror is called on 4's new left child, 7. Its children 6 and 9 change places, so 7 now has 9 on its left and 6 on its right.

  4. 4729node613
    node
    9
    swaps so far
    3
    level order
    4, 7, 2, 9, 6, 1, 3

    4mirror(9) swaps 9's two null children, which changes nothing. Its calls on those nulls return at once.

  5. 47296node13
    node
    6
    swaps so far
    4
    level order
    4, 7, 2, 9, 6, 1, 3

    5mirror(6) is a leaf too, and nothing changes. The whole left side of the root is now finished.

  6. 472node9631
    node
    2
    swaps so far
    5
    level order
    4, 7, 2, 9, 6, 3, 1

    6Back at the root, mirror is called on its right child, 2. Its children 1 and 3 change places, so 2 now has 3 on its left and 1 on its right.

  7. 472963node1
    node
    3
    swaps so far
    6
    level order
    4, 7, 2, 9, 6, 3, 1

    7mirror(3) is a leaf, so its swap of two nulls changes nothing.

  8. 4729631node
    node
    1
    swaps so far
    7
    level order
    4, 7, 2, 9, 6, 3, 1

    8mirror(1) is the last leaf. Every node has had its children swapped exactly once.

  9. 4729631
    swaps
    7
    null calls
    8
    new nodes
    0

    9mirror(4) returns the same root. The tree now reads 4, 7, 2, 9, 6, 3, 1, the mirror image, built with no new nodes.

Let us read the important frames back. In the second frame a single swap at the root moves both whole subtrees, and the level order already starts 4, 7, 2. The third and sixth frames each swap one pair of leaves, and between them the level order becomes 4, 7, 2, 9, 6, 3, 1.

The leaf frames look as if nothing happens, and that is right. A leaf's two children are both null, and swapping null with null changes nothing; the two calls on those nulls return at once. Counting them, the method made 7 swaps and 15 calls, one for each node and one for each of the 8 null children.

6The complete Java program

Here is the whole program. It has a small Node class, the recursive mirror, an iterative version that uses a queue, and a levelOrder helper for printing. main prints the tree, its mirror, then mirrors it again with the iterative version, which restores the original, and finally mirrors an empty tree.

Java
import java.util.*;
public class MirrorTree {
static class Node {
int val;
Node left, right;
Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; }
Node(int val) { this(val, null, null); }
}
// Swaps the children of every node, in place, and returns the same root.
static Node mirror(Node node) {
if (node == null) return null; // an empty tree is its own mirror
Node saved = node.left; // keep the left child before we overwrite it
node.left = node.right;
node.right = saved;
mirror(node.left); // now mirror each child's own subtree
mirror(node.right);
return node;
}
// Iterative version with a queue: no recursion depth to worry about.
static Node mirrorIterative(Node root) {
Deque<Node> queue = new ArrayDeque<>();
if (root != null) queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.poll();
Node saved = n.left;
n.left = n.right;
n.right = saved;
if (n.left != null) queue.add(n.left);
if (n.right != null) queue.add(n.right);
}
return root;
}
static List<Integer> levelOrder(Node root) {
List<Integer> out = new ArrayList<>();
Deque<Node> queue = new ArrayDeque<>();
if (root != null) queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.poll();
out.add(n.val);
if (n.left != null) queue.add(n.left);
if (n.right != null) queue.add(n.right);
}
return out;
}
public static void main(String[] args) {
Node root = new Node(4, new Node(2, new Node(1), new Node(3)), new Node(7, new Node(6), new Node(9)));
System.out.println(levelOrder(root)); // [4, 2, 7, 1, 3, 6, 9]
System.out.println(levelOrder(mirror(root))); // [4, 7, 2, 9, 6, 3, 1]
System.out.println(levelOrder(mirrorIterative(root))); // [4, 2, 7, 1, 3, 6, 9]
System.out.println(levelOrder(mirror(null))); // []
}
}

Let us read mirror in the order it runs. The first line is the base case. If node is null, there is nothing to swap, and the mirror of an empty tree is empty, so we return null. This line also ends the recursion at every leaf's missing children.

Next, saved = node.left keeps the old left child, because the very next line overwrites node.left with node.right. Then node.right = saved puts the old left child on the right. The swap is done. The two calls mirror(node.left) and mirror(node.right) then go into the new children, so the same swap happens at every node below. Finally we return node, the same root we were given, so a caller can write root = mirror(root) or chain it as main does.

mirrorIterative does the same swaps without recursion. It puts the root in a queue, a line where the first one in is the first one out. Each time round the loop it takes a node from the front, swaps its children with the same saved trick, and adds the non-null children to the back. Every node passes through the queue once, so every node is swapped once.

levelOrder prints the values row by row using the same queue idea. So main prints [4, 2, 7, 1, 3, 6, 9], then [4, 7, 2, 9, 6, 3, 1]. Mirroring twice gives back the original, so the third line matches the first, which makes a handy test. The empty tree prints [].

7How much it costs, and the cases at the edges

Let us count on the example first. mirror made 7 swaps, one per node, and 15 calls, including the 8 calls on null children. For a tree of n nodes there are always n + 1 null children, so the method makes 2n + 1 calls, each doing a constant amount of work. The time is O(n), the same as the copy, but without making n new nodes.

The extra space is the recursion. Each call waits while it mirrors its children, so the number of waiting calls is at most the height h of the tree, its number of levels, which gives O(h). For a balanced tree, filled level by level, h is about log n. For a tree that is really a chain, h is n, and a very deep chain can overflow Java's call stack; the queue version holds at most one level at a time instead, O(w) for the widest level w.

Comparing the ways to mirror a tree
ApproachTimeExtra spaceChanges the tree?
Build a mirrored copyO(n)O(n) new nodes plus O(h)no
Recursive swap, before or after the childrenO(n)O(h) call stackyes
Swap in the middle, in-orderO(n)O(h)yes, but the answer is wrong
Queue, swap as each node leaves itO(n)O(w) for the widest levelyes

The edge cases need no special code. An empty tree returns null from the first line. A single node swaps its two null children with each other, harmlessly, and comes back unchanged. A tree with only left children becomes a tree with only right children, which is a good test of a hand-written version.

If the original must be kept, we use mirrorCopy instead, at the cost of O(n) new nodes. Either way, a quick check is that mirroring twice must give back the tree we started with.

8Follow-up questions

How do you check whether a tree is symmetric, a mirror of itself?

We compare the tree with its own mirror without building it. A helper takes two nodes, one from each side. If both are null, they match. If exactly one is null, they do not. Otherwise their values must be equal, the first node's left must match the second node's right, and the first node's right must match the second node's left, each checked by the same helper. We start it with the root's left and right children. Each node is visited once, so it is O(n) time and O(h) space.

Does the order of traversal matter for the iterative version?

No. Any walk that takes each node exactly once and swaps its children works, because the swap at one node never depends on another. So a stack, giving a depth-first order, is as good as our queue. The choice only changes the memory: a stack holds about one path from the root plus the siblings along it, and a queue holds about one level. The in-order trouble does not arise here, because each node is swapped when it is taken out, and its children are added after the swap.

How would you check that two trees are mirror images of each other?

With the same two-node helper as the symmetry check, started on the two roots instead of on one root's children. Two empty trees are mirrors, an empty and a non-empty tree are not, and otherwise the values must match, the first tree's left must mirror the second tree's right, and its right must mirror the second's left. It is O(n) time, and it leaves both trees unchanged.

9Conclusion

We mirrored a binary tree in place by swapping the two children of every node, keeping the old left child in a spare variable during the swap, and recursing into both children, with null as the base case. It takes O(n) time and O(h) stack space, and a queue version avoids deep recursion. The clue to remember is an answer for a tree that is described by the answers for its subtrees, which points to tree recursion; and when the work at each node is independent, any walk that visits each node once will do, except swapping in the middle of an in-order walk.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm that I may change the tree in place and return its root, and that an empty tree is allowed. Building a mirrored copy is correct and is the answer if the original must survive, but it allocates n new nodes when only the child references are in the wrong places.

Then, if they want more

So I will swap in place. The mirror of a tree is its root with the mirrored right subtree on the left and the mirrored left subtree on the right, which gives a direct recursion. If the node is null, I return null.

Otherwise I save the left child, set left to the right child, set right to the saved left child, and then mirror both children. I need the saved variable, otherwise both sides end up pointing at the same subtree.

Swapping before or after visiting the children both work, but swapping between them, in-order, mirrors one subtree twice and the other not at all. Each node is visited once, so it is O(n) time, and the recursion depth is the height, so O(h) space.

For a very deep tree I would use a queue: take a node, swap its children, and add them to the queue.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 24 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Convert a binary tree into its mirror image.": https://scrivio-interview-library.netlify.app/data-structures/solutions/convert-a-binary-tree-into-its-mirror-image-5177fc/