Skip to main content

10. Same Tree

easyAsked at Activision

Decide whether two binary trees are structurally identical — Activision uses this to test recursive equality checks akin to scene-graph diffing.

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 (same structure and same node values).

Constraints

  • 0 <= nodes <= 100
  • -10^4 <= Node.val <= 10^4

Examples

Example 1

Input
p=[1,2,3], q=[1,2,3]
Output
true

Example 2

Input
p=[1,2], q=[1,null,2]
Output
false

Approaches

1. Serialize and compare

Serialize both trees with markers and compare strings.

Time
O(n)
Space
O(n)
function ser(n) { return n ? `${n.val},${ser(n.left)},${ser(n.right)}` : '#'; }
return ser(p) === ser(q);

Tradeoff:

2. Parallel recursion

If both null true; if one null false; otherwise values must match and both children recurse true.

Time
O(n)
Space
O(h)
function isSameTree(p, q) {
  if (!p && !q) return true;
  if (!p || !q) return false;
  return p.val === q.val
      && isSameTree(p.left, q.left)
      && isSameTree(p.right, q.right);
}

Tradeoff:

Activision-specific tips

Activision wants you to short-circuit on first mismatch — they treat needless full-tree work as the same code smell they hunt in their replication systems.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Same Tree and other Activision interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →