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.
Compare values at each node. Recurse on both left and both right subtrees.
Three base cases cover all null combinations — after that, just compare values and recurse on both children.
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)Practice Same Tree and similar Trees problems with flashcards. Build pattern recognition through active recall.
Practice this problem