Most Frequent Subtree Sum LeetCode solution in Java

1
class Solution {
2
public int[] findFrequentTreeSum(TreeNode root) {
3

4
HashMap<Integer, Integer> map = new HashMap<>();
5
int sum = sum(root, map);
6
int max = 0;
7
int count = 0;
8
for (Integer key : map.keySet()) {
9
max = Math.max(max, map.get(key));
10
}
11

12
for (Integer key : map.keySet()) {
13
if (max == map.get(key)) {
14
count++;
15
}
16
}
17
int[] ans = new int[count];
18
int counter = 0;
19
for (Integer key : map.keySet()) {
20
if (max == map.get(key)) {
21
ans[counter++] = key;
22
}
23
}
24

25
return ans;
26
}
27

28
public int sum(TreeNode root, HashMap<Integer, Integer> map) {
29
if (root == null) return 0;
30
int lh = sum(root.left, map);
31
int rh = sum(root.right, map);
32
map.put(lh + rh + root.val, map.getOrDefault(lh + rh + root.val, 0) + 1);
33
return lh + rh + root.val;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0