Skip to content

Commit 44ed0c3

Browse files
Accepted
1 parent d194824 commit 44ed0c3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

problems/src/PathSumIII.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* Created by gouthamvidyapradhan on 08/04/2017.
6+
* Accepted
7+
*/
8+
9+
public class PathSumIII
10+
{
11+
/**
12+
*
13+
*/
14+
public static class TreeNode
15+
{
16+
int val;
17+
TreeNode left;
18+
TreeNode right;
19+
TreeNode(int x) { val = x; }
20+
}
21+
22+
private Map<Integer, Integer> pathCount = new HashMap<>();
23+
private int totalCount;
24+
25+
public static void main(String[] args) throws Exception
26+
{
27+
TreeNode node = new TreeNode(1);
28+
System.out.println(new PathSumIII().pathSum(node, 0));
29+
}
30+
31+
public int pathSum(TreeNode root, int sum)
32+
{
33+
if(root == null) return 0;
34+
dfs(root, sum, 0);
35+
return totalCount;
36+
}
37+
38+
private void dfs(TreeNode root, int target, int pSum)
39+
{
40+
if(root != null)
41+
{
42+
pSum += root.val;
43+
if(pSum == target) totalCount++;
44+
totalCount += pathCount.getOrDefault(pSum - target, 0);
45+
pathCount.put(pSum, pathCount.getOrDefault(pSum, 0) + 1);
46+
dfs(root.left, target, pSum);
47+
dfs(root.right, target, pSum);
48+
pathCount.put(pSum, pathCount.get(pSum) - 1);
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)