题目
思路
本题在树上使用前缀和思想
当遍历到某个节点n时,看以当前节点为路径的终点时,有多少个向下的路径和为target
:
假设从根到当前节点的路径和为sum,则看从根到当前节点之前的路径,有多少条和为
sum - target
例如上图中,10 -> 5 -> 2 -> 1
这条路径,从根10
到叶子节点1
的sum为18
,从根到根的sum为
sum - target = 10
,因此找到一条路径和为8的路径,即5 -> 2 -> 1
代码
public int pathSum(TreeNode root, int targetSum) {
HashMap<Long, Integer> map = new HashMap<>();
map.put((long)0,1);
return process(root,targetSum,0,map);
}
private int process(TreeNode root, int sum, long path, Map<Long,Integer> map) {
if (root == null) {
return 0;
}
path += root.val;
// 看以root为结尾,有多少条路径的和为sum
int count = map.getOrDefault(path - sum,0);
if(!map.containsKey(path)) {
map.put(path,1);
} else {
map.put(path,map.get(path) + 1);
}
count += process(root.left,sum,path,map);
count += process(root.right,sum,path,map);
map.put(path,map.get(path) - 1);
return count;
}