3. Same Tree
easyAsked at JetBrainsCheck whether two binary trees are structurally and value-equal node-by-node — JetBrains uses this to gauge whether you can compare PSI subtrees for incremental reparse.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees, return true if they are identical — same shape and same values at every node.
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 to strings and compare; wasteful allocation for large trees.
- Time
- O(n)
- Space
- O(n)
const ser = (n) => n ? `${n.val},${ser(n.left)},${ser(n.right)}` : '#';
return ser(p) === ser(q);Tradeoff:
2. Parallel DFS
Recurse both trees in lockstep, short-circuiting on first mismatch. Same shape as JetBrains' AST diff walkers used during incremental parsing.
- 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:
JetBrains-specific tips
JetBrains expects you to mention this is exactly the shape of incremental-reparse diffing — short-circuit early and avoid building intermediate strings.
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 JetBrains interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →