Same Tree

Check whether two binary trees have the same shape and the same values in every place.

Given the roots of two binary trees p and q, return true if the two trees are the same, and false otherwise. Two trees are the same when they have the same shape and the nodes in matching places hold the same values. Each tree below is written row by row from the top, with null where a child is missing.

Example 1
Input: p = [1, 2, 3], q = [1, 2, 3]
Output: true
Example 2
Input: p = [1, 2], q = [1, null, 2]
Output: false
Explanation: same values, but 2 is a left child in one tree and a right child in the other.
Solution

The Idea

Imagine two family trees drawn on paper, and you want to know whether one is a copy of the other. Listing the names would not settle it. You would check that the same name sits at the top, then compare what hangs below it on the left, then on the right.

In Example 1, both trees are written [1, 2, 3]. The node at the top of each, called the root, holds 1. Below it hang two nodes, called its children: 2 on the left and 3 on the right. Every position holds the same value in both trees, so the answer is true.

Example 2 is less obvious. Tree p = [1, 2] has the root 1 with a left child 2. Tree q = [1, null, 2] has the root 1, no left child, and a right child 2. Both trees hold the values 1 and 2, so what makes them different? Look at the picture below.

Tree p = [1, 2] and tree q = [1, null, 2] side by side. The roots 1 and 1 match. The left children are 2 in p and none in q, so one node is missing and the trees differ.

The teal box, labelled roots: 1 and 1, shows that the tops match. The orange box, labelled left children: 2 and none, compares what sits to the left of each root. Tree p has 2 there and tree q has nothing, so the trees differ, even though their values are the same.

Notice that the left child 2 is itself the top of a smaller tree, called the left subtree, and the same goes for the right side. So two trees are the same when their roots hold equal values, their left subtrees are the same, and their right subtrees are the same. That is the original question again, asked about smaller trees, and it ends when a comparison reaches a missing node.

Solution Approach

Turning that idea into code means settling three things: how to compare two trees position by position, what to do when a node is missing, and how to stop at the first difference. A simpler plan, comparing lists of values, comes first, because it shows why positions matter.

Comparing lists of values

Why not write each tree out as a list of its values and compare the lists? Listing a tree root first, then its left subtree, then its right subtree, is called a preorder walk. For Example 2 it gives [1, 2] for both trees, so the lists match although the trees do not. The list forgets which side each child was on.

Writing a marker such as null for every missing child would fix that. It would still store two extra lists, and comparing the nodes directly gives the same answer without them.

Comparing node by node

So how do we compare positions directly? A method isSameTree(p, q) takes one node from each tree, both in the same position. It checks their two values, then calls itself on the two left children and again on the two right children. A method that calls itself on smaller parts of its input is called recursive.

Missing nodes

What happens when the calls reach the bottom of a tree? A missing child is null in Java. If both nodes are null, both subtrees there are empty, and they match. If only one is null, one tree has a node where the other has none, as in the picture.

The check p == q covers both cases as soon as either node is null. Two null references are equal, while null and a real node are not.

Stopping at the first difference

Do we need to look at every node? One difference is enough to answer false. Joining the three checks with && stops there, because Java skips the right side of && when the left side is already false. For [1, 2, 1] and [1, 1, 2], the left children 2 and 1 differ, so the right children are never compared.

Java Solution

The method isSameTree works in these steps:

  1. First, check whether either node, p or q, is null. If so, return p == q, which is true only when both are null.
  2. Otherwise both nodes exist, so compare their values, p.val and q.val.
  3. If the values are equal, call isSameTree(p.left, q.left) to compare the two left subtrees.
  4. If those match too, call isSameTree(p.right, q.right) for the two right subtrees. The method returns true only when all three checks pass.

Around the method, a small TreeNode class holds one node with its value and two children, and a build helper turns the row-by-row form, such as [1, null, 2], into a tree.

The main method runs both examples, two trees with the same values on swapped sides, two empty trees, an empty tree against [1], and two trees that differ only in their deepest node.

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

public class SameTree {

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

    public static boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) {
            return p == q;          // true only when both are missing
        }
        return p.val == q.val
                && isSameTree(p.left, q.left)
                && isSameTree(p.right, q.right);
    }

    // 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;
    }

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

Running it prints:

Output
true
false
false
true
false
false

The second line, false, is Example 2, where 2 sits on the left in one tree and on the right in the other. The third line is false for [1, 2, 1] against [1, 1, 2], which already fails at the left children 2 and 1.

The fourth line is true: two empty trees match, because both roots are null and p == q holds. The fifth is false, since [1] has a root where the empty tree has none. The last line compares [1, 2, 3, 4] with [1, 2, 3, 5]. Every node matches until the bottom row, where 4 and 5 differ, and that single node is enough to make the answer false.

Complexity

Each call does a fixed amount of work for one pair of nodes, and the calls go down the trees one level at a time.

  • Time: O(n), where n is the number of nodes in the smaller tree, because each call compares one pair of nodes in matching places and the calls stop where either tree runs out.
  • Space: O(h), where h is the number of levels in the shorter tree, because the calls still waiting form one chain from the root down to the pair being compared, one call per level.

Comparing a tree with its own mirror uses the same recursion with crossed children: Symmetric Tree.