Compare recursively with careful base cases:
def 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:
Both null → same (base case)
Exactly one null → different
Values differ → different
If none of these trigger, recurse on both pairs of children. Both pairs must match.
Time: where and are tree sizes. Space: for recursion.