Same Tree
Easy
Topics
Given the roots of two binary trees p and q, return true if they are structurally identical and the nodes have the same values.
Example 1
p
q
Same values in the same positions, so the answer is
true. The recursion compares the two roots and then the two left subtrees and two right subtrees in lockstep — reaching null on both sides at the same time is the success case.Tree given in level-order (breadth-first);
null marks a missing child.Input: p = [1,2,3], q = [1,2,3] Output: true
Example 2
p
q
The trees diverge at the shaded node, so the answer is
false. Shape counts as much as values: one node missing where the other has a child is already a mismatch.Input: p = [1,2], q = [1,null,2] Output: false
Constraints
- 0 <= number of nodes <= 100
- -10^4 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two trees are the same when their roots match AND their left subtrees match AND their right subtrees match — a clean recursive definition.
Approach
- If both nodes are null, they match.
- If exactly one is null, or values differ, they do not match.
- Otherwise recurse on both pairs of children.
Dry Run
p = 1 2 3 q = 1 2 3
root 1 == 1, recurse into both pairs of children
root.L 2 == 2, recurse
root.L.L both null -> true
root.L.R both null -> true
root.R 3 == 3, recurse
root.R.L both null -> true
root.R.R both null -> true
-> true
p = 1 2 q = 1 null 2
root 1 == 1, recurse into both pairs of children
root.L 2 vs null -> false
-> false, and the right pair is never examined
The second case is why structure is compared rather than contents. Both trees
hold exactly the values 1 and 2, and a traversal-based comparison could easily
call them equal; walking them in lockstep catches that the 2 hangs off different
sides.
The recursion bottoms out on `both null`, which is a result and not a case to
skip. Delete that line and every comparison eventually walks off the end of both
trees and falls through to false -- two identical single-node trees report false.
The null check has to precede `.val`. Reorder it so the values are compared
first and the identical pair above still returns true, because it never meets a
one-sided null; but 1 2 against 1 null 2 raises
AttributeError: 'NoneType' object has no attribute 'val'. A reordering that
passes the easy case and crashes on the interesting one.Complexity
- Time — O(n): each pair of nodes is compared once.
- Space — O(h): recursion stack.
Common Pitfalls
- Both-null is
True, not a case to skip. Without it, every comparison eventually reaches two empty children and returns false, so even identical trees report false. - Check for null before touching
.val. Comparing values first raisesAttributeError: 'NoneType' object has no attribute 'val'the moment one tree is shorter -- structure has to be compared, not just contents.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p, q):
if not p and not q: return True
if not p or not q or p.val!=q.val: return False
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)return true;
if(p==null||q==null||p.val!=q.val)return false;
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p&&!q)return true;
if(!p||!q||p->val!=q->val)return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/ var isSameTree = function(p, q) {
if(!p&&!q)return true;
if(!p||!q||p.val!==q.val)return false;
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
};