Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
Examples 1
Input:
5 / \ 2 -3return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5 / \ 2 -5return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
先求出所有节点的和的值,然后排序后找出频数最大的数
public class Solution {
List<Integer> sum = new ArrayList<>();
public int[] findFrequentTreeSum(TreeNode root) {
helper(root);
Collections.sort(sum);
List<Integer> l = new ArrayList<>();
int most=0, cnt=0, pre=Integer.MAX_VALUE;
for(int i : sum){
if(i==pre){
cnt++;
}else{
cnt = 1;
pre = i;
}
if(cnt==most){
l.add(pre);
}else if(cnt>most){
l.clear();
l.add(pre);
most = cnt;
}
}
int[] ans = new int[l.size()];
int index=0;
for(int i : l){
ans[index++] = i;
}
return ans;
}
private int helper(TreeNode root){
if(root==null) return 0;
int left = helper(root.left);
int right = helper(root.right);
int temp = left + right + root.val;
sum.add(temp);
return temp;
}
}
也可以用map来保存频数信息,同时保存最大频数,之后遍历相等则输出
public class Solution {
int max = 0;
public int[] findFrequentTreeSum(TreeNode root) {
if(root==null) return new int[0];
Map<Integer, Integer> map = new HashMap<>();
helper(root, map);
List<Integer> res = new LinkedList<>();
for(Map.Entry<Integer, Integer> me: map.entrySet()){
if(me.getValue()==max) res.add(me.getKey());
}
return res.stream().mapToInt(i->i).toArray();
}
private int helper(TreeNode n, Map<Integer, Integer> map){
int left = (n.left==null) ? 0 : helper(n.left, map);
int right = (n.right==null) ? 0 : helper(n.right, map);
int sum = left + right + n.val;
map.put(sum, map.getOrDefault(sum,0)+1);
max = Math.max(max, map.get(sum));
return sum;
}
}