首页 > 代码库 > Path Sum

Path Sum

# Definition for a  binary tree nodeclass TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution:    # @param root, a tree node    # @param sum, an integer    # @return a boolean    def hasPathSum(self, root, sum):        if root==None :                return False                    if root.val==sum and root.left is None and root.right is None:            return True        #elif  root.val==sum:  #出现负数的情况,这里就不对了,可能这个条件成立了,但是子树之和为0 也是正确的        #    return False        else:
      
return (self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val))

 

Path Sum