508. Most Frequent Subtree Sum

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容