508. Most Frequent Subtree Sum
Problem:
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:
Input:
5 / \ 2 -3return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
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.
Analysis:
Very straight forward divide and conquer. Use a map to record the frequency of sum. Mean while, use keep updating the most occurrence.
Solution:
1: class Solution {
2: int max = 0;
3: public int[] findFrequentTreeSum(TreeNode root) {
4: Map<Integer, Integer> map = new HashMap<>();
5: List<Integer> list = new ArrayList<>();
6: helper(root, map);
7: for (int sum: map.keySet()) {
8: int freq = map.get(sum);
9: if (freq == max) {
10: list.add(sum);
11: }
12: }
13: int[] res = new int[list.size()];
14: for (int i = 0; i < res.length; i++) {
15: res[i] = list.get(i);
16: }
17: return res;
18: }
19: private int helper(TreeNode root, Map<Integer, Integer> map) {
20: if (root == null) return 0;
21: int left = helper(root.left, map);
22: int right = helper(root.right, map);
23: int sum = root.val + left + right;
24: int count = map.getOrDefault(sum, 0) + 1;
25: map.put(sum, count);
26: max = Math.max(max, count);
27: return sum;
28: }
29: }
评论
发表评论