Same Tree

25 min · isSameTree()

Two company org charts can contain the same names and still describe different teams: where each person sits matters as much as the names themselves.

Given the roots p and q, return true only when the two binary trees are structurally identical — every corresponding position is either empty in both trees or holds nodes with the same value.

Keep both parts of that rule in view:

  • Equal values in a different shape don't make the trees equal.
  • Matching shapes with one different value don't make them equal.
  • Two empty trees are the same.
  • One empty tree and one non-empty tree are different.

Constraints

  • 0 <= number of nodes in each tree <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

Preserve the gaps

If you serialize each tree level by level, keep markers for missing children. Without those gaps, a left child and a right child can look identical.

Compare a pair of positions

For two current nodes, there are three useful cases: both are absent, exactly one is absent, or both exist. Decide each case before moving deeper.

All three checks must survive

When both nodes exist, their values must match, their left subtrees must match, and their right subtrees must match. One failed check settles the answer.

Follow-up

Could you perform the simultaneous comparison with an explicit stack so a very deep tree never depends on the language's recursion limit?

Visible cases

Examples

Example 1

ready
Input
p = [
  1,
  2,
  3
]
q = [
  1,
  2,
  3
]
Expected
true
Why
every value and child position matches

Example 2

ready
Input
p = [
  1,
  2
]
q = [
  1,
  null,
  2
]
Expected
false
Why
the value 2 sits on opposite sides of the roots

Example 3

ready
Input
p = []
q = []
Expected
true
Why
two empty trees have the same shape and values

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite