InterviewPrepKit

Home / Coding / Trees

Same Tree

easy Original β†—
Solving tips
  • Recognize this as lockstep parallel DFS: the definition ('same value AND left subtrees same AND right subtrees same') is directly the recursion.
  • Handle the three node-pair cases in order: both None (match), exactly one None (fail), then compare values and recurse.
  • Target O(min(n,m)) time with short-circuiting via `and`, and O(h) recursion space; an iterative queue-of-pairs is the follow-up.
  • Pitfall: comparing only value-sequences (preorder/inorder) accepts differently-shaped trees, so nulls must participate in the comparison.

Problem

Given the roots of two binary trees p and q, decide whether the two trees are identical: they must have exactly the same shape, and every corresponding pair of nodes must hold the same value. Return True if they are identical, False otherwise.

Examples

Example 1

Input: p = [1,2,3], q = [1,2,3]
Output: True

Both trees are a root 1 with left child 2 and right child 3 β€” same structure, same values.

Example 2

Input: p = [1,2], q = [1,null,2]
Output: False

Both trees contain the values {1, 2}, but p’s 2 is a left child while q’s 2 is a right child β€” the shapes differ.

Example 3

Input: p = [1,2,1], q = [1,1,2]
Output: False

Same shape, but the children’s values are swapped: 2 vs 1 on the left, 1 vs 2 on the right.

Constraints

  • The number of nodes in each tree is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4

The tiny bound means any O(n) traversal is fine β€” the problem is about getting the structural comparison right, not about speed.

Think about it first

Hint 1 When are two trees the same? Think about what must hold at the roots, and what must hold for the subtrees.
Hint 2 There are three cases for the pair (p, q): both are None, exactly one is None, or both exist. Only the last case needs further work.
Hint 3 Two trees are the same iff both roots are None, or both exist with equal values AND their left subtrees are the same AND their right subtrees are the same. That sentence is the recursion.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.