-
Notifications
You must be signed in to change notification settings - Fork 0
/
week6 437. Path Sum III
41 lines (35 loc) · 972 Bytes
/
week6 437. Path Sum III
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int count = 0;
public int pathSum(TreeNode root, int sum) {
Map<Integer, Integer> cache = new HashMap<>();
cache.put(0, 1);
helper(root, 0, sum, cache);
return count;
}
public void helper(TreeNode root, int curSum, int target, Map<Integer, Integer> cache){
if (root == null){
return;
}
curSum += root.val;
if (cache.containsKey(curSum - target)){
count += cache.get(curSum - target);
}
if (!cache.containsKey(curSum)){
cache.put(curSum, 1);
}else{
cache.put(curSum, cache.get(curSum) + 1);
}
helper(root.left, curSum, target, cache);
helper(root.right, curSum, target, cache);
cache.put(curSum, cache.get(curSum) - 1);
}
}