572. Subtree of Another Tree

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.


Note: For an easy problem, I struggled a lot. I failed to see that the
     recursion needs to be on the main function and not just matches()


def isSubtree(root: Optional[TreeNode], subRoot: Optional[TreeNode]):
       
    def matches(r, s):            
        if r is None and s is None:
            return True
        if r is None or s is None:
            return False
       
        return  r.val == s.val \
                and matches(r.left, s.left) \
                and matches(r.right, s.right)
       
                       
    if matches(root, subRoot):
        return True      
    if root is None:
        return False
    return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)

     

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break