题目
给出一个二叉树和一个目标值值,找到所有的路径,该路径上的节点数值和为目标值。路径不一定非要用根节点开始。举个例子:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
Python题解
class Solution(object):
def helper(self, root, target, so_far, cache):
if root:
complement = so_far + root.val - target
if complement in cache:
self.result += cache[complement]
cache.setdefault(so_far + root.val, 0)
cache[so_far + root.val] += 1
self.helper(root.left, target, so_far + root.val, cache)
self.helper(root.right, target, so_far + root.val, cache)
cache[so_far + root.val] -= 1
def pathSum(self, root, sum_val):
"""
:type root: TreeNode
:type sum_val: int
:rtype: int
"""
self.result = 0
self.helper(root, sum_val, 0, {0: 1})
return self.result