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 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.
Solution:Hashmap + Post-order Traversal
post-order遍历可以一次求得各个subtree的sum,将(sum, count) 保存到hashmap中 并记录max_count。最后再遍历hashmap找到所有value为max_count的key(sum),加入到result_list
Time Complexity: O(N)
Space Complexity: O(N + N),一个hashmap,一个递归缓存
Solution Code:
class Solution {
Map<Integer, Integer> sum_count_map;
int max_count;
public int[] findFrequentTreeSum(TreeNode root) {
sum_count_map = new HashMap<Integer, Integer>();
max_count = 0;
// post-order traverse to build sum_count_map
postOrder(root);
//check same sum in sum_count_map
List<Integer> result_list = new ArrayList<>();
for (int key: sum_count_map.keySet()) {
if(sum_count_map.get(key) == max_count) {
result_list.add(key);
}
}
// return format: convert result_list to result_array
int[] result_array = new int[result_list.size()];
for (int i = 0; i < result_list.size(); i++) {
result_array[i] = result_list.get(i);
}
return result_array;
}
private int postOrder(TreeNode node) {
if(node == null) return 0;
int left = postOrder(node.left);
int right = postOrder(node.right);
int sum = left + right + node.val;
int count = sum_count_map.getOrDefault(sum, 0) + 1;
sum_count_map.put(sum, count);
max_count = Math.max(max_count, count);
return sum;
}
}