Same Tree
Easy · Trees
Jump to codeDetermine whether two binary trees have identical structure and matching values at every corresponding node.
Examples
Example 1
p = [1,2,3] q = [1,2,3]
Output: true
Example 2
p = [1,2] q = [1,null,2]
Output: false
Constraints
- 0 <= The number of nodes in both trees <= 100
- -100 <= Node.val <= 100
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Need a hint?
Null positions are part of the structure.
Real tree interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Lowest Common Manager of a Group of Employees in an Org ChartAmazon
- Repeatedly Delete Leaves Matching a Target Value From a Binary TreeGoogle
- Merge two N-ary trees by key rulesLinkedIn
Solution approach
If both nodes are null, they match. If exactly one is null or their values differ, they do not. Otherwise require both pairs of left children and both pairs of right children to match recursively.
Complexity
O(min(n, m)) time for nonempty inputs and O(min(h1, h2)) stack space.
Python reference solution
def isSameTree(p, q):
if p is None or q is None:
return p is q
return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
JavaScript solution
function isSameTree(p, q) {
if (!p || !q) return p === q;
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
Java solution
import java.util.*;
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == q;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p || !q) return p == q;
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
2,
3
],
[
1,
2,
3
]
]true
[
[
1,
2
],
[
1,
null,
2
]
]false
[
[
1,
2,
1
],
[
1,
1,
2
]
]false
[ [], [] ]
true
[
[
1
],
[]
]false
Drafts are saved per language in this browser when storage is available.