-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day-8 Path Sum III
74 lines (66 loc) · 1.66 KB
/
Day-8 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int result=0;
public int pathSum(TreeNode root, int sum) {
dfs(root,sum);
return result;
}
void dfs(TreeNode node,int sum){
if(node==null){
return;
}
sum(node,sum);
dfs(node.left,sum);
dfs(node.right,sum);
}
void sum(TreeNode n,int s){
if(n==null){
return;
}
int temp=s-n.val;
if(temp==0){
result++;
}
sum(n.left,temp);
sum(n.right,temp);
}
}
class Solution {
int count = 0;
int k;
HashMap<Integer, Integer> h = new HashMap();
public void preorder(TreeNode node, int currSum) {
if (node == null)
return;
currSum += node.val;
if (currSum == k)
count++;
count += h.getOrDefault(currSum - k, 0);
h.put(currSum, h.getOrDefault(currSum, 0) + 1);
preorder(node.left, currSum);
preorder(node.right, currSum);
// remove the current sum from the hashmap
// in order not to use it during
// the parallel subtree processing
h.put(currSum, h.get(currSum) - 1);
}
public int pathSum(TreeNode root, int sum) {
k = sum;
preorder(root, 0);
return count;
}
}