Symmetric Tree

Check whether a binary tree is a mirror image of itself around a line through its root.

Given the root of a binary tree, where each node has at most a left child and a right child, return true if the tree is a mirror image of itself, and false otherwise. Picture a vertical line through the root: the tree is symmetric when its left side, flipped over that line, matches its right side in shape and in values. The tree has at least one node.

The examples list the tree row by row, each row from left to right, with null where a child is missing.

Example 1
Input: root = [1, 2, 2, 3, 4, 4, 3]
Output: true
Example 2
Input: root = [1, 2, 2, null, 3, null, 3]
Output: false
Explanation: both 3s are right children, so the two sides are not mirror images.
Solution

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 1: the tree 1, 2, 2, 3, 4, 4, 3 with a mirror line through the root. The two 3s are the outer pair and the two 4s the inner pair. Example 2: the left 3 faces an empty spot marked with a question mark, and the right 3 has no partner.

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), takes one node from each side and answers whether the subtrees starting at them mirror each other. isSymmetric asks it about root.left and root.right.

A simpler plan also works: build a flipped copy of the whole tree, as Invert Binary Tree does, then check that the copy equals the original, as Same Tree does. That plan makes a new node for every node in the tree. Walking both sides together answers the same question without any copy.

Missing nodes

What if a or b is null, meaning there is no node there? If both are missing, two empty spots mirror each other. That is how the check ends below the 3s and 4s of Example 1. If only one is missing, a node faces an empty spot, as each 3 does in Example 2, and the answer is false.

One line covers both cases. When a or b is null, return a == b. With at least one of the two missing, that comparison is true only when both are null.

Pairing the children

Once a and b hold equal values, which children come next? The outer pair is a.left with b.right, and the inner pair is a.right with b.left, exactly as the picture marks them for Example 1. Both pairs must mirror each other. Joining the checks with && stops at the first false, so a mismatch near the top ends the walk early.

Java Solution

The method isSymmetric works in these steps:

  1. First, isSymmetric(root) passes the root's two children, root.left and root.right, to the helper mirror. The tree has at least one node, so reading root.left is safe.
  2. Inside mirror(a, b), check for missing nodes first: if a or b is null, return a == b.
  3. Otherwise compare a.val with b.val, and return false if they differ.
  4. If the values are equal, call mirror on the outer pair, a.left and b.right, then on the inner pair, a.right and b.left. Return true only when both calls do.

The class also has a small TreeNode class, holding a value and its left and right children, and a helper, build, that makes a tree from the row-by-row form of the examples.

The main method runs both examples, a single node, a root with two different children, and two trees that hold the same values 1, 2, 2, 3, 3 in different places.

Java
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:

Output
true
false
true
false
true
false

Example 1 gives true on the first line, and Example 2 gives false on the second. The single node on the third line is symmetric: both of its children are missing, so mirror(null, null) returns true. On the fourth line, the root's children 2 and 3 differ, so mirror returns false without going any deeper.

Look at the last two lines. In [1, 2, 2, 3, null, null, 3], the 3s are the left child of the left 2 and the right child of the right 2, an outer pair, so the answer is true. In [1, 2, 2, 3, null, 3], both 3s are left children, and the last line is false.

Why must the children cross? A version of mirror that compares a.left with b.left and a.right with b.right checks whether the two sides are equal copies, not mirror images. Run on the two examples, that version prints false for Example 1 and true for Example 2, both wrong.

Complexity

The work is one call of mirror for each pair of nodes that face each other across the mirror line.

  • Time: O(n), because mirror 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.
  • 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.