10. Same Tree
easyAsked at CanvaDecide if two binary trees are structurally and value-equal — Canva uses this to test recursion hygiene around shape comparisons in template trees.
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: identical structure and identical node values at every position.
Constraints
0 <= 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, compare strings.
- Time
- O(n)
- Space
- O(n)
const ser = t => !t ? '#' : `${t.val},${ser(t.left)},${ser(t.right)}`;
return ser(p) === ser(q);Tradeoff:
2. Recursive structural check
If both null, equal. If one null, unequal. Otherwise compare values + recurse both children.
- Time
- O(n)
- Space
- O(h)
function isSame(p, q) {
if (!p && !q) return true;
if (!p || !q) return false;
return p.val === q.val && isSame(p.left, q.left) && isSame(p.right, q.right);
}Tradeoff:
Canva-specific tips
Canva interviewers like base cases stated explicitly because template-diff systems hinge on rigorous null/empty handling.
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 Canva interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →