11. Same Tree
easyAsked at WixDetermine if two binary trees are identical; Wix uses the same shape check when diffing draft vs published 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 structurally identical and node values match.
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 + compare
Serialize each tree to a string and compare.
- Time
- O(n)
- Space
- O(n)
function ser(n){return n? `(${n.val},${ser(n.left)},${ser(n.right)})` : 'N'}; return ser(p)===ser(q);Tradeoff:
2. Recursive structural
Recurse on children only when both exist with same val.
- Time
- O(n)
- Space
- O(h)
function isSameTree(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);
}Tradeoff:
Wix-specific tips
Wix favors the structural recursion answer — they like seeing you handle the null/null base case explicitly because it mirrors their null-component slots.
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 Wix interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →