10. Same Tree
easyAsked at BookingDecide if two binary trees match — Booking uses this to gauge whether you can compare cached vs live availability 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 the nodes have the same value.
Constraints
0 <= each tree's node count <= 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
Preorder-serialize each tree to a string and compare — uses extra memory.
- Time
- O(n)
- Space
- O(n)
const ser = r => !r ? '#' : `${r.val},${ser(r.left)},${ser(r.right)}`;
return ser(p) === ser(q);Tradeoff:
2. Recursive structural compare
Walk both trees in parallel and short-circuit on mismatch.
- 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:
Booking-specific tips
Booking will steer this toward 'how would you diff a cached availability tree against a fresh one' — emphasize the early-exit on mismatch for low-latency search responses.
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →