public class Solution {
int max =
1;
public int[] findFrequentTreeSum(TreeNode root) {
Map<Integer,Integer>
map =
new HashMap<>();
dfs(
map,root);
int maxi =
0;
for(Integer i :
map.keySet()) {
if(
map.get(i) > max) {
max =
map.get(i);
maxi = i;
}
}
if(max ==
1) {
int[] a =
new int[
map.size()];
int j =
0;
for(Integer i:
map.keySet()) {
a[j++] = i;
}
return a;
}
else {
List<Integer>
list =
new ArrayList<>();
for(Integer i:
map.keySet()) {
if(
map.get(i) == max) {
list.add(i);
}
}
return list.stream().mapToInt(i->i).toArray();
}
}
public int dfs(Map<Integer,Integer>
map, TreeNode root) {
if(root == null) {
return 0;
}
int sum = dfs(
map, root.left) + dfs(
map,root.right) + root.val;
map.put(sum,
map.getOrDefault(sum,
0)+
1);
return sum;
}
}
转载请注明原文地址: https://ju.6miu.com/read-25586.html