Same Tree

Check if two binary trees are identical.

Pattern

Parallel Recursion

This problem follows the Parallel Recursion pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Compare values at each node. Recurse on both left and both right subtrees.

Key Insight

Three base cases cover all null combinations — after that, just compare values and recurse on both children.

Step-by-step

  1. 1Base case: if both nodes are null, return true
  2. 2If one is null and the other isn't, return false
  3. 3If values differ, return false
  4. 4Recursively compare left subtrees and right subtrees

Pseudocode

def isSameTree(p, q):
    if not p and not q: return true
    if not p or not q: return false
    return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(h)
More Trees Problems

Master this pattern with YeetCode

Practice Same Tree and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem