題目
給出一個二叉樹和一個目標值值,找到所有的路徑,該路徑上的節點數值和爲目標值。路徑不一定非要用根節點開始。舉個例子:
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