11. Same Tree
easyAsked at DuolingoCheck whether two binary trees have identical structure and values.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees p and q, return true if they are structurally identical and the corresponding nodes have the same value, false otherwise.
Constraints
0 <= total nodes <= 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 with null sentinels and compare strings.
- Time
- O(n)
- Space
- O(n)
const ser = n => n? `(${n.val},${ser(n.left)},${ser(n.right)})` : '#';
return ser(p) === ser(q);Tradeoff:
2. Recursive DFS
Both null is equal; one null isn't; otherwise compare values and recurse on both subtrees.
- Time
- O(n)
- Space
- O(h)
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Tradeoff:
Duolingo-specific tips
Duolingo regression-checks skill-tree clones after content edits, so structural-equality DFS is a real internal subroutine—mention the null-sentinel symmetry.
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 Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →