考点 | 难度 |
---|---|
DFS | Medium |
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
对每个node, 如果从root到node的所有和为currentsum, 如果这条path上有满足条件的说明有oldsum = currentsum - target, 所以只需要数oldsum出现的次数。
离开path之前需要清空cache。
class Solution(object):
def pathSum(self, root, target):
# define global result and path
self.result = 0
cache = {0:1}
# recursive to get result
self.dfs(root, target, 0, cache)
# return result
return self.result
def dfs(self, root, target, currPathSum, cache):
# exit condition
if root is None:
return
# calculate currPathSum and required oldPathSum
currPathSum += root.val
oldPathSum = currPathSum - target
# update result and cache
self.result += cache.get(oldPathSum, 0)
cache[currPathSum] = cache.get(currPathSum, 0) + 1
# dfs breakdown
self.dfs(root.left, target, currPathSum, cache)
self.dfs(root.right, target, currPathSum, cache)
# when move to a different branch, the currPathSum is no longer available, hence remove one.
cache[currPathSum] -= 1