题目
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.
答案
class Solution {
public int[] findFrequentTreeSum(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, List<Integer>> map2 = new HashMap<>();
if(root == null) return new int[]{};
int ret = recur(root, map);
int max = -1;
for(Integer x : map.keySet()) {
Integer freq = map.get(x);
List<Integer> list = map2.get(freq);
if(list == null) {
list = new ArrayList<>();
map2.put(freq, list);
}
list.add(x);
if(freq > max)
max = freq;
}
List<Integer> list = map2.get(max);
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
return arr;
}
public int recur(TreeNode root, Map<Integer, Integer> map) {
if(root == null) return 0;
int left = recur(root.left, map);
int right = recur(root.right, map);
int subtreesum = left + right + root.val;
Integer freq = map.get(subtreesum);
if(freq == null)
map.put(subtreesum, 1);
else
map.put(subtreesum, freq + 1);
return subtreesum;
}
}