← DSA
EASY

Same Tree

PracticeNeetCode ↗LeetCode ↗

Given the roots of two binary trees p and q, return true if they are structurally identical and every corresponding node holds the same value.

Example

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

Key Pointers

Step-by-Step Analysis

  1. If both p and q are None, return True.
  2. If exactly one of p or q is None, return False.
  3. If p.val != q.val, return False.
  4. Return isSameTree(p.left, q.left) and isSameTree(p.right, q.right).

Complexity

Time: O(min(n, m)) — Space: O(min(h_p, h_q))

Code

def isSameTree(p: TreeNode | None, q: TreeNode | None) -> bool:
    if not p and not q:
        return True
    if not p or not q:
        return False
    if p.val != q.val:
        return False
    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)

Code Explanation

How the solution above works, piece by piece.

  1. Both empty: identical at this position → True.
  2. Exactly one empty: shapes differ → False.
  3. Both present but values differ → False.
  4. Otherwise both left subtrees and both right subtrees must match; and short-circuits on the first mismatch.
  5. O(n) time for n nodes, O(height) stack.

Visual Walkthrough

Running it on p = [1, 2, 3], q = [1, 2, 3]:

Two trees compared node by nodep123q123
The recursion walks both trees in lockstep (dotted lines): same position, same value, then the same check on the left children and on the right children.
matched

Video Explanation

NeetCode — Same Tree, LeetCode 100