【leetcode】Python實現-112.路徑總和
阿新 • • 發佈:2019-02-08
描述
我
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
sum-=root.val
if sum == 0:
if root.left is None and root.right is None:
return True
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
稍微優化
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None :
return False
if sum == root.val and root.left is None and root.right is None:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)