Invert Binary Tree

Mirror a binary tree by swapping the left and right children of every node.

Given the root of a binary tree, turn the tree into its mirror image and return the root. In the mirror image, every node has its left and right children swapped. The trees below are written row by row, from the top, with null for a missing child.

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]
Example 3
Input: root = []
Output: []
Solution

The Idea

Draw a family tree on thin paper, then turn the sheet over and hold it up to the light. The drawing is the same, but everything that was on the left is now on the right. Inverting a tree does that to its links.

Start by reading Example 1 as a picture. The array [4, 2, 7, 1, 3, 6, 9] lists the tree one row at a time. 4 is alone on the top row, and the top node is called the root. On the next row, 2 hangs below 4 on the left and 7 on the right; they are the two children of 4. The last row holds 1 and 3, the children of 2, then 6 and 9, the children of 7. Each node has at most two children, a left one and a right one, which is what makes the tree binary.

Look at the picture below. The tree on the left is the input, and the tree on the right is the output, [4, 7, 2, 9, 6, 3, 1].

Example 1 before and after inverting. Before, 4 has 2 on the left and 7 on the right. After, 7 is on the left and 2 on the right, and inside each of them the children have swapped too: 2 now has 3 then 1, and 7 has 9 then 6.

The orange nodes are 2 with its children 1 and 3. Together they are the left subtree of 4: a node plus everything below it. The teal nodes, 7 with 6 and 9, are the right subtree. In the tree labelled "after", the orange group has moved to the right of 4 and the teal group to the left.

Swapping 2 and 7 is not the whole job, though. Inside the orange group, 1 was on the left of 3, and after the flip 3 is on the left of 1. The teal group changed in the same way: 9 now comes before 6. So how do we mirror the orange group itself?

It is the same problem again, only on a smaller tree with 2 at the top. That gives the whole rule: to mirror a tree, mirror its left subtree and its right subtree, then hang each one on the opposite side of the top node. A method that solves a problem by calling itself on smaller parts is called recursive, and this rule turns straight into one.

Solution Approach

Turning that rule into code means settling three things: where the calls stop, in which order to mirror and swap, and whether to build new nodes; a version without recursion follows as an option.

Where the calls stop

Each call works on a smaller subtree, so where does it end? Below 1, 3, 6 and 9 there are no children at all. In Java, a missing child is a null link, and a null tree is already its own mirror. So the method returns null right away when it gets one. This one check also covers Example 3, where the whole tree is empty.

Mirroring first, then swapping

Which comes first, the swap at the top or the work inside the subtrees? Either order works, as long as every node gets its children swapped once. The method below mirrors both subtrees first and keeps them in two local variables, left and right. Only then does it change the links of the top node. Both variables matter, because the two old links of the top node must both be read before either one is overwritten.

Reusing the same nodes

Does the mirror need a new tree? No. Every node keeps its value and only its two links change, so the method moves the existing links around and returns the same root it was given. No node is created or lost.

Without recursion (optional)

Each call waits until the calls for its subtrees return, and Java keeps every waiting call in memory. For a tree that is one long chain, that is one waiting call per node. If that is a concern, a loop can do the same work: keep a queue of nodes still to visit, starting with the root. A queue hands its items back in the order they went in. Take a node from the queue, swap its two children, and add any child that is not null to the queue.

Java Solution

The method invertTree works in these steps:

  1. First, if root is null, return null: there is nothing to mirror.
  2. Otherwise, call invertTree(root.left) and keep the mirrored left subtree in a variable named left. Then call invertTree(root.right) and keep the mirrored right subtree in right.
  3. Hang right on the left side with root.left = right, and left on the right side with root.right = left.
  4. Return root, the same node that came in, now with its children swapped.

Around the method, a small TreeNode class holds a value and its two links. The helper build turns the row-by-row array into a tree, and show prints a tree back in that form.

The main method runs the three examples, a tree of one node, and the tree [1, 2, null, 3], where every node has only a left child.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class InvertBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;                             // an empty tree mirrors to itself
        }
        TreeNode left = invertTree(root.left);       // mirror both subtrees first
        TreeNode right = invertTree(root.right);
        root.left = right;                           // then put them on opposite sides
        root.right = left;
        return root;
    }

    // Builds a tree from its row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode node = queue.poll();
            if (values[i] != null) {
                node.left = new TreeNode(values[i]);
                queue.add(node.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                node.right = new TreeNode(values[i]);
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }

    // Prints a tree in the same row-by-row form, dropping trailing nulls.
    static String show(TreeNode root) {
        List<String> out = new ArrayList<>();
        List<TreeNode> order = new ArrayList<>();
        if (root != null) {
            order.add(root);
        }
        for (int k = 0; k < order.size(); k++) {
            TreeNode node = order.get(k);
            if (node == null) {
                out.add("null");
                continue;
            }
            out.add(String.valueOf(node.val));
            order.add(node.left);
            order.add(node.right);
        }
        while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
            out.remove(out.size() - 1);
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(show(invertTree(build(4, 2, 7, 1, 3, 6, 9))));
        System.out.println(show(invertTree(build(2, 1, 3))));
        System.out.println(show(invertTree(build())));
        System.out.println(show(invertTree(build(5))));
        System.out.println(show(invertTree(build(1, 2, null, 3))));
    }
}

Running it prints:

Output
[4, 7, 2, 9, 6, 3, 1]
[2, 3, 1]
[]
[5]
[1, null, 2, null, 3]

The first line, [4, 7, 2, 9, 6, 3, 1], is the tree labelled "after" in the picture. The third line, [], is Example 3: the method got null and returned it at once. The single node in [5] has two null children, so swapping them changes nothing.

Look at the last line. In the input [1, 2, null, 3], 2 is the left child of 1, the null says 1 has no right child, and 3 is the left child of 2. After mirroring, both links point right, so the output needs a null before 2 and before 3: [1, null, 2, null, 3].

Why keep left and right in variables at all? It looks shorter to write root.left = invertTree(root.right); followed by root.right = invertTree(root.left);. But the second line reads root.left after the first line has already replaced it. By then root.left holds the mirrored right subtree, so that subtree is mirrored again and hung on the right as well, while the original left subtree is dropped. Run on the same inputs, that version prints [4, 7, 7, 9, 9, 9, 9] for Example 1, [2, 3, 3] for Example 2, and only [1] for the last tree.

Complexity

Each node is handled by one call, and the extra memory is the chain of calls that are waiting for their subtrees.

  • Time: O(n), because invertTree runs once for each of the n nodes and once for each null child below them, and each run does only two assignments besides its two calls.
  • Space: O(h) for a tree with h rows, because the calls waiting at any moment are the ones on a single path from the root down. That is about log n for a full tree like Example 1, and n for a tree that is one long chain.

Checking whether a tree already equals its own mirror is Symmetric Tree.