-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
39 lines (34 loc) · 973 Bytes
/
Copy pathSolution.java
File metadata and controls
39 lines (34 loc) · 973 Bytes
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
import java.util.*;
public class Solution
{
private int maxCount = Integer.MIN_VALUE;
public int[] findFrequentTreeSum(TreeNode root)
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
getSums(root, map);
List<Integer> list = new ArrayList<>();
map.forEach((k, v) ->
{
if (v == maxCount)
{
list.add(k);
}
});
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++)
{
result[i] = list.get(i);
}
return result;
}
private int getSums(TreeNode root, Map<Integer, Integer> map)
{
int sum = root == null ? 0 : root.val + getSums(root.left, map) + getSums(root.right, map);
if (root != null)
{
map.put(sum, map.getOrDefault(sum, 0) + 1);
maxCount = Math.max(maxCount, map.get(sum));
}
return sum;
}
}