Data Structures19 sections · 729 units
Open in Course

Same Tree Solution

Recursive comparison

Compare recursively with careful base cases:

function isSameTree(p, q):
    if p == null and q == null:
        return true
    if p == null or q == null:
        return false
    if p.val != q.val:
        return false
    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)

Three checks:

1.1. Both null → same (base case)

2.2. Exactly one null → different

3.3. Values differ → different

If none of these trigger, recurse on both pairs of children. Both pairs must match.

Time: O(min(n,m))O(\min(n, m)) where nn and mm are tree sizes.

Space: O(min(h1,h2))O(\min(h_1, h_2)) for recursion.