Same Tree¶

Check if two binary trees are equivalent¶

Idea of the algorithm is to recursively 1) check if the current node val are equivalent and 2) check if left and right subtrees are also equivalent¶
In [ ]:
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    def helper(p, q):
        if p and q:
            return(p.val==q.val and helper(p.left, q.left) and helper(p.right, q.right))
        else:
            return((not p) and (not q))
    return(helper(p, q))