-
Notifications
You must be signed in to change notification settings - Fork 46
/
_437.java
41 lines (36 loc) · 1.1 KB
/
_437.java
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
import java.util.HashMap;
import java.util.Map;
/**
* LeetCode 437 - Path Sum III
*
* One-pass DFS
*/
public class _437 {
int ans = 0;
Map<Integer, Integer> dfs(TreeNode root, int sum) {
if (root == null) return new HashMap<>();
Map<Integer, Integer> left = dfs(root.left, sum);
Map<Integer, Integer> right = dfs(root.right, sum);
Map<Integer, Integer> map = new HashMap<>();
map.put(root.val, 1);
for (Map.Entry<Integer, Integer> entry : left.entrySet()) {
int cb = entry.getKey() + root.val;
int wb = entry.getValue();
map.putIfAbsent(cb, 0);
map.put(cb, map.get(cb) + wb);
}
for (Map.Entry<Integer, Integer> entry : right.entrySet()) {
int cb = entry.getKey() + root.val;
int wb = entry.getValue();
map.putIfAbsent(cb, 0);
map.put(cb, map.get(cb) + wb);
}
ans += map.getOrDefault(sum, 0);
return map;
}
public int pathSum(TreeNode root, int sum) {
ans = 0;
dfs(root, sum);
return ans;
}
}