Skip to main content

10. Same Tree

easyAsked at Dropbox

Determine if two binary trees are identical in structure and values; Dropbox uses it as a primer for comparing two file-tree snapshots during sync.

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 values.

Constraints

  • 0 <= nodes per tree <= 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

Convert each tree to a string (with null markers) 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. Synchronous DFS

Recursively check val equality and the two pairs of subtrees. Returns early on first mismatch.

Time
O(min(n,m))
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:

Dropbox-specific tips

Dropbox interviewers ask 'what about when only structure differs but values match?' to test base-case ordering — write the null-check before the val check.

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 Dropbox interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →