sagelearnai

Same Tree

Difficulty: Easy · Pattern: Trees & BST · LeetCode #100

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

Examples

text
p = [1,2,3], q = [1,2,3]      →  true
p = [1,2],   q = [1,null,2]   →  false   (2 is a left child in one, right child in the other)
p = [1,2,1], q = [1,1,2]      →  false

Hints

  1. Two empty trees are equal. One empty and one non-empty are not.
  2. If the roots match, the trees are equal exactly when both pairs of subtrees are equal.

Approach

This is the simplest structural recursion there is, and the template for many tree problems:

  1. Both null → true.
  2. Exactly one null, or the values differ → false.
  3. Otherwise → same(p.left, q.left) && same(p.right, q.right).

The && short-circuits, so we stop at the first mismatch. An iterative version pushes (p, q) pairs onto a stack and applies the same three checks.

Complexity

Time: O(min(n, m)), since we stop at the first difference. Space: O(h) recursion depth.

Python solution
def isSameTree(p, q):
    if not p and not q:
        return True
    if not p or not q or p.val != q.val:
        return False
    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
JavaScript solution
function isSameTree(p, q) {
  if (!p && !q) return true;
  if (!p || !q || p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}