-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMain.java
55 lines (48 loc) · 1.52 KB
/
Main.java
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
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MostFrequentSubtreeSum508 {
class Solution {
int maxx = Integer.MIN_VALUE;
HashMap<Integer, Integer> map;
public int[] findFrequentTreeSum(TreeNode root) {
this.map = new HashMap<>();
maxx = Integer.MIN_VALUE;
if (root == null) {
return new int[0];
}
helper(root);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int freq = entry.getValue();
if (freq > maxx) {
maxx = freq;
}
}
LinkedList<Integer> list = new LinkedList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int sum = entry.getKey();
int freq = entry.getValue();
if (freq == maxx) {
list.add(sum);
}
}
int arr[] = new int[list.size()];
int index = 0;
for (int val : list) {
arr[index ++] = val;
}
return arr;
}
public int helper (TreeNode root) {
if (root == null) {
return 0;
}
int sum = root.val
+ helper(root.left)
+ helper(root.right);
int freq = this.map.getOrDefault(sum, 0) + 1;
this.map.put(sum, freq);
return sum;
}
}
}