Skip to content

Commit fa5f45b

Browse files
author
Tushar Roy
committed
Count sum path solution
1 parent 03551d1 commit fa5f45b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.interview.tree;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* https://leetcode.com/problems/path-sum-iii/description/
8+
*/
9+
public class CountPathSum {
10+
public int pathSum(Node root, int sum) {
11+
Map<Integer, Integer> map = new HashMap<>();
12+
map.put(0, 1);
13+
return countPathSum(root, sum, map, 0);
14+
}
15+
16+
private int countPathSum(Node root, int sum, Map<Integer, Integer> map, int prefixSum) {
17+
if (root == null) {
18+
return 0;
19+
}
20+
21+
prefixSum += root.data;
22+
int count = map.getOrDefault(prefixSum - sum,0);
23+
map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1);
24+
count += countPathSum(root.left, sum, map, prefixSum) + countPathSum(root.right, sum, map, prefixSum);
25+
map.put(prefixSum, map.getOrDefault(prefixSum, 1) - 1);
26+
return count;
27+
}
28+
}
29+

0 commit comments

Comments
 (0)