Python easy to understand 11 lines - 60ms solution O(n)


  • 0
    A


    class Solution:
    def hasPathSum(self, root, sum):
    """
    :type root: TreeNode
    :type sum: int
    :rtype: bool
    """
    if(not root):
    return False
    else:
    tmp = root.val
    if(sum-tmp == 0 and not root.left and not root.right):
    return True
    if(self.hasPathSum(root.left, sum - tmp)):
    return True
    elif(self.hasPathSum((root.right), sum-tmp)):
    return True
    return False


Log in to reply
 

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