We compare the roots and then recursively compare their left and right subtrees.
- If both
pandqare None, they are the same (True). - If only one is None or their values differ, they are not the same (False).
- Return
is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right).
- Time Complexity: O(N).
- Space Complexity: O(H).
def is_same_tree(p, q):
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)