Python recursive solution with clear comments


  • 0
    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            # if root not exist, there is no solution
            if not root:
                return False
            # if the leaf node has value == current sum, we got the path
            if root.val == sum and root.left is None and root.right is None:
                return True
            # recursively find possible paths in left and right child
            return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)
    

Log in to reply
 

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