Reference from https://leetcode-cn.com/problems/path-sum-iii/solution/qian-zhui-he-di-gui-hui-su-by-shi-huo-de-xia-tian/
prefix and -Refers to the path to the current element之前所有元素的和
- Under the same path, if there are two numbers
前缀和是相同的
, the sum of the elements between these nodes is zero- Then, under the same path, if the prefix sum of node A is different from the prefix sum of node B by target, the sum of the elements located between node A and node B is target. (If the current known path is A->C->B, the prefix sum of A and B is different from target, then the sum of C+B is target)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
num_dict = {
}
num_dict[0] = 1 # 初始化,前缀和为0的一条路径
return self.recursionPathSum(root, num_dict, sum, 0)
def recursionPathSum(self, node, num_dict, target, currSum):
if (node == None): return 0
res = 0
currSum += node.val # 当前路径和
'''
重点:
如果此前有和为currSum-target,而当前的和又为currSum,两者的差就肯定为target了
所以根据当前num_dict的值进行搜索,将结果加入res中
'''
res += num_dict.get(currSum-target, 0)
num_dict[currSum] = num_dict.get(currSum, 0)+1
res += self.recursionPathSum(node.left, num_dict, target, currSum)
res += self.recursionPathSum(node.right, num_dict, target, currSum)
num_dict[currSum] -= 1 # 回到本层,去掉本层的路径和
return res