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 pq
Example 1
Output: true
Example 2
Output: false
Explanation: same values, but 2 is a left child in one tree and a right child in the other.
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]
Example 2 is less obvious. Tree p = [1, 2]q = [1, null, 2]
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 pq
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]
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)
Missing nodes
What happens when the calls reach the bottom of a tree? A missing child is nullnullnull
The check p == qnullnullnull
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 &&&&[1, 2, 1][1, 1, 2]
Java Solution
The method isSameTree
- First, check whether either node,
orp , isq . If so, returnnull , which is true only when both arep == q .null - Otherwise both nodes exist, so compare their values,
andp.val .q.val - If the values are equal, call
to compare the two left subtrees.isSameTree(p.left, q.left) - If those match too, call
for the two right subtrees. The method returns true only when all three checks pass.isSameTree(p.right, q.right)
Around the method, a small TreeNodebuild[1, null, 2]
The main[1]
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:
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][1, 1, 2]
The fourth line is true: two empty trees match, because both roots are nullp == q[1][1, 2, 3, 4][1, 2, 3, 5]
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: