和112、113题类似
不过这一题更难一些,需要进行双重递归:即对每个节点做递归,再以该节点为起点进行DFS,搜寻满足条件的路径
class Solution(object):
def __init__(self):
self.count = 0
def pathSum(self, root, sum):
if not root:
return 0
def helper(root, sum):
if not root:
return
if sum - root.val == 0:
self.count += 1
# if root.left:
helper(root.left, sum - root.val)
# if root.right:
helper(root.right, sum - root.val)
#双重递归
helper(root, sum)
self.pathSum(root.left, sum)
self.pathSum(root.right, sum)
return self.count