Python easy recursive search


  • 0
    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            if root is None:
                return False
            if self.search(root, 0, sum):
                return True
            else:
                return False
         
        def search(self, root, sum, target):
            if root.left == root.right == None and sum + root.val == target:
                return True
            elif root.left is not None and root.right is not None:
                if self.search(root.left, sum + root.val, target) or self.search(root.right, sum + root.val, target):
                    return True
                else:
                    return False
            elif root.left is not None:
                if self.search(root.left, sum + root.val, target):
                    return True
                else:
                    return False
            elif root.right is not None:
                if self.search(root.right, sum + root.val, target):
                    return True
                else:
                    return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.