11. Same Tree
easyAsked at GojekDecide whether two binary trees are structurally identical with matching node values.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees p and q, write a function to check if they are the same tree. They are the same if they are structurally identical and the nodes have the same value.
Constraints
The number of nodes in both trees is in [0, 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 each tree with nulls included and string-compare.
- Time
- O(n)
- Space
- O(n)
const s = t => !t ? '#' : `(${t.val},${s(t.left)},${s(t.right)})`;
return s(p) === s(q);Tradeoff:
2. Parallel recursion
Recurse both trees together; both null is equal, one null is unequal, otherwise check value and recurse children.
- 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:
Gojek-specific tips
Gojek's multi-service catalog often replicates config trees across regions, so a short-circuiting structural compare is exactly the shape of code that ships.
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 Gojek interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →