Leetcode 112. Path Sum

时间:2021-12-11 09:10:51

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

解法: 使用递归。在例子中,存在一个从root出发的,sum=22的路径 <=> 存在从4出发的,sum=22-4的路径 or 存在从8出发的,sum=22-8的路径

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

也可以使用DFS+backtracking

 class Solution(object):
def hasPathSum(self, root, s):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False res = []
self.dfs(root, s, [root.val], res)
return any(res) def dfs(self, root, s, path, res): if not root.left and not root.right and sum(path) == s:
res.append(True) if root.right:
self.dfs(root.right, s, path+[root.right.val], res)
if root.left:
self.dfs(root.left, s, path+[root.left.val], res)