-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path437. Path Sum III
41 lines (30 loc) · 1.12 KB
/
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
class Solution {
Map<Long, Integer> hmap;
int count;
public int pathSum(TreeNode root, int targetSum) {
hmap = new HashMap<>();
count = 0;
dfs(root, 0, targetSum);
return count;
}
private void dfs(TreeNode root, long prefixSum, int targetSum) {
// base case
if (root == null) return;
prefixSum += root.val;
// If map contains a sum equal to (prefixSum - targetSum), we need to increment count that many times
if (hmap.containsKey(prefixSum-targetSum)) {
count += hmap.get(prefixSum-targetSum);
}
// There can be cases when the prefixSum is directly equal to targetSum, we need to increment count
if (targetSum == prefixSum) {
count++;
}
// Update the prefixSum till current node and it's count
hmap.put(prefixSum, hmap.getOrDefault(prefixSum, 0) + 1);
// Recurse
dfs(root.left, prefixSum, targetSum);
dfs(root.right, prefixSum, targetSum);
// Backtrack
hmap.put(prefixSum, hmap.get(prefixSum) - 1);
}
}