-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPath Sum-III
94 lines (77 loc) · 2.3 KB
/
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.
Example 2:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
Constraints:
The number of nodes in the tree is in the range [0, 1000].
-109 <= Node.val <= 109
-1000 <= targetSum <= 1000
Solution:
/**
* 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 total=0;
int target=0;
HashMap<Long,Integer> hash=new HashMap<>();
public int pathSum(TreeNode root, int targetSum) {
target=targetSum;
long a=0;
hash.put(a,1);
dfs(root,0);
return total;
}
public void dfs(TreeNode root,long sum){
if(root==null){
return;
}
sum=sum+root.val;
if(hash.containsKey(sum-target)){
total=total+hash.get(sum-target);
if(hash.containsKey(sum)){
int d=hash.get(sum);
hash.replace(sum,(d+1));
}
else{
hash.put(sum,1);
}
}
else{
if(hash.containsKey(sum)){
int d=hash.get(sum);
hash.replace(sum,(d+1));
}
else{
hash.put(sum,1);
}
}
int d=hash.get(sum);
dfs(root.left,sum);
dfs(root.right,sum);
if(d<=1){
hash.remove(sum);
}
else{
hash.replace(sum,(d-1));
}
sum=sum-root.val;
return;
}
}