10. Same Tree
easyAsked at IndeedCheck if two binary trees are structurally and value-wise identical — Indeed uses it as a building block for duplicate-posting tree comparison.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees p and q, return true if they are the same tree. Two trees are the same when their structure is identical and corresponding nodes have equal values.
Constraints
0 <= nodes per tree <= 100-10^4 <= node.val <= 10^4
Examples
Example 1
p = [1,2,3], q = [1,2,3]trueExample 2
p = [1,2], q = [1,null,2]falseApproaches
1. Serialize and compare
Serialize both trees to strings then compare.
- Time
- O(n)
- Space
- O(n)
const serial = (n) => n ? `${n.val},${serial(n.left)},${serial(n.right)}` : '#';
return serial(p) === serial(q);Tradeoff:
2. Synchronous recursion
Compare current nodes, then recurse on both pairs of children.
- Time
- O(n)
- Space
- O(h)
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q) return false;
return p.val === q.val
&& isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}Tradeoff:
Indeed-specific tips
Indeed wants the early-exit short-circuit explained out loud — they apply the same logic when comparing canonical job-posting trees for dedup.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Same Tree and other Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →