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
Example 1
Output: [4, 7, 2, 9, 6, 3, 1]
Example 2
Output: [2, 3, 1]
Example 3
Output: []
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]
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]
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 nullnullnull
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, leftright
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
Java Solution
The method invertTree
- First, if
isroot , returnnull : there is nothing to mirror.null - Otherwise, call
and keep the mirrored left subtree in a variable namedinvertTree(root.left) . Then callleft and keep the mirrored right subtree ininvertTree(root.right) .right - Hang
on the left side withright , androot.left = right on the right side withleft .root.right = left - Return
, the same node that came in, now with its children swapped.root
Around the method, a small TreeNodebuildshow
The main[1, 2, null, 3]
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:
[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][]null[5]null
Look at the last line. In the input [1, 2, null, 3]nullnull[1, null, 2, null, 3]
Why keep leftrightroot.left = invertTree(root.right);root.right = invertTree(root.left);root.leftroot.left[4, 7, 7, 9, 9, 9, 9][2, 3, 3][1]
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
runs once for each of the n nodes and once for eachinvertTree child below them, and each run does only two assignments besides its two calls.null - 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