4. Same Tree
easyAsked at RevolutCheck whether two binary trees are structurally and value-identical, a Revolut warm-up that mirrors comparing two ledger snapshots for reconciliation drift.
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 if they are structurally identical and the nodes have the same values.
Constraints
0 <= 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
Serialize both trees to strings and compare equality.
- 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 DFS
Walk both trees in lockstep and short-circuit on the first mismatch. Linear time, stack depth equals tree height.
- 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:
Revolut-specific tips
Revolut frames this as comparing two ledger trees from different regions — explicitly state that minor units must use integer equality, never float, before you write the recursion.
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 Revolut interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →