Same Tree
Difficulty: Easy
You're given the roots of two binary trees. Return true if they're identical: the same shape, with the same value at every matching node. Otherwise return false.
Examples
Input: p = [1,2,3], q = [1,2,3]
Output: true
Every node in the same position holds the same value.
Input: p = [1,2], q = [1,null,2]
Output: false
Both trees have a node valued 2, but in p it's a left child while in q it's a right child - the structures don't match.
Input: p = [1,2,1], q = [1,1,2]
Output: false
The structures match, but the values at the second and third positions are swapped between the two trees.
Constraints
The number of nodes in both trees is in the range [0, 100].
-10^4 <= Node.val <= 10^4
Approach
Two trees match when either:
- both roots are null, or
- both roots exist with equal values, and their left subtrees match, and their right subtrees match.
So compare the current pair of nodes, then recurse into the matching left and right children.
Solutions
Recursive DFS
If both nodes are null, they match. If only one is null, or the values differ, they don't. Otherwise, check that both left subtrees and both right subtrees match.
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function isSameTree(p, q) {
if (p === null && q === null) return true;
if (p === null || q === null) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Time: O(n) — where n is the number of nodes in the smaller tree · Space: O(h) — recursion stack depth, where h is the shorter tree's height
Iterative BFS
Walk both trees together with a queue of node pairs. Pop a pair, compare it, and queue its child pairs (left-with-left, right-with-right).
function isSameTree(p, q) {
const queue = [[p, q]];
while (queue.length > 0) {
const [nodeP, nodeQ] = queue.shift();
if (nodeP === null && nodeQ === null) continue;
if (nodeP === null || nodeQ === null) return false;
if (nodeP.val !== nodeQ.val) return false;
queue.push([nodeP.left, nodeQ.left]);
queue.push([nodeP.right, nodeQ.right]);
}
return true;
}Time: O(n) — where n is the number of nodes in the smaller tree · Space: O(n) — the queue can hold up to a whole level of node pairs