Symmetric Tree
Check whether a binary tree is a mirror image of itself around a line through its root.
Given the roottruefalse
The examples list the tree row by row, each row from left to right, with null
Example 1
Output: true
Example 2
Output: false
Explanation: both 3s are right children, so the two sides are not mirror images.
The Idea
Hold a drawing up to a mirror and its left and right swap places. A symmetric tree looks the same after that swap. In Example 1, the root 1 has two children, 2 and 2. The left 2 has the children 3 and 4, and the right 2 has 4 and 3: the same values in the opposite order.
Look at the picture below. On the left, the dashed mirror line runs down through the root of Example 1. Fold the tree along it and every node lands on a node with the same value. The two 3s, marked outer pair, sit at the far edges, and the two 4s, marked inner pair, sit next to the line.
Example 2, on the right of the picture, has similar values but a different shape. Each 2 has only a right child, a 3. Folded over the line, the left 3 lands on the spot marked with a question mark, where the right side has no node. The right 3, marked no partner, has nothing facing it either.
So which nodes have to match? First, the root's two children must hold equal values. One level down, the pairs cross over the line. The left child of the left 2 faces the right child of the right 2, and the right child of the left 2 faces the left child of the right 2.
Each of those children can have children of its own. The left 2 together with everything below it, its children 3 and 4, is called the root's left subtree, and the right 2 with its children is the right subtree. The real question is whether the left subtree and the right subtree are mirror images of each other.
And that question repeats itself. Two subtrees are mirror images when their top nodes hold the same value, their outer children start mirror subtrees, and their inner children start mirror subtrees. A method that answers a question by asking the same question about smaller pieces, calling itself, is called recursive.
Solution Approach
Turning that idea into code means settling three things: what the recursive method compares, what it does when a node is missing, and which children it pairs up next.
Comparing two subtrees at once
What should the recursive method take? Looking at one node cannot tell whether the tree is symmetric, because symmetry is about two nodes on opposite sides of the mirror line. So a helper, mirror(a, b)isSymmetricroot.leftroot.right
A simpler plan also works: build a flipped copy of the whole tree, as
Missing nodes
What if abnullfalse
One line covers both cases. When abnulla == bnull
Pairing the children
Once aba.leftb.righta.rightb.left&&false
Java Solution
The method isSymmetric
- First,
passes the root's two children,isSymmetric(root) androot.left , to the helperroot.right . The tree has at least one node, so readingmirror is safe.root.left - Inside
, check for missing nodes first: ifmirror(a, b) ora isb , returnnull .a == b - Otherwise compare
witha.val , and returnb.val if they differ.false - If the values are equal, call
on the outer pair,mirror anda.left , then on the inner pair,b.right anda.right . Returnb.left only when both calls do.true
The class also has a small TreeNodeleftrightbuild
The main
import java.util.ArrayDeque;
import java.util.Queue;
public class SymmetricTree {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static boolean isSymmetric(TreeNode root) {
return mirror(root.left, root.right);
}
// Are these two subtrees mirror images of each other?
private static boolean mirror(TreeNode a, TreeNode b) {
if (a == null || b == null) {
return a == b; // true only when both are missing
}
return a.val == b.val
&& mirror(a.left, b.right) // outer pair
&& mirror(a.right, b.left); // inner pair
}
// Builds a tree from the row-by-row form, with null for a missing child.
static TreeNode build(Integer... values) {
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int i = 1;
while (i < values.length) {
TreeNode node = queue.remove();
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;
}
public static void main(String[] args) {
System.out.println(isSymmetric(build(1, 2, 2, 3, 4, 4, 3)));
System.out.println(isSymmetric(build(1, 2, 2, null, 3, null, 3)));
System.out.println(isSymmetric(build(1)));
System.out.println(isSymmetric(build(1, 2, 3)));
System.out.println(isSymmetric(build(1, 2, 2, 3, null, null, 3)));
System.out.println(isSymmetric(build(1, 2, 2, 3, null, 3)));
}
}
Running it prints:
true
false
true
false
true
false
Example 1 gives truefalsemirror(null, null)truemirrorfalse
Look at the last two lines. In [1, 2, 2, 3, null, null, 3]true[1, 2, 2, 3, null, 3]false
Why must the children cross? A version of mirrora.leftb.lefta.rightb.rightfalsetrue
Complexity
The work is one call of mirror
- Time: O(n), because
pairs every node of the tree with the one node opposite it, so a tree of n nodes needs at most about n / 2 value comparisons, and a mismatch ends the walk sooner.mirror - Space: O(h), because the recursion goes down both sides together, one call per level, so at most h calls are waiting for an answer at once, where h is the number of levels in the tree.