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.

Examples 2
Input:

  5
 /  
2   -5

return [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.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
12     private int mostCount = Integer.MIN_VALUE;
13     
14     public int[] findFrequentTreeSum(TreeNode root) {
15         helper(root);
16         return getMostSum();
17     }
18     
19     private int helper(TreeNode root) {
20         if (root == null) return 0;
21         
22         int maxSum = root.val + helper(root.left) + helper(root.right);
23         map.put(maxSum, map.containsKey(maxSum) ? map.get(maxSum) + 1 : 1);
24         mostCount = Math.max(mostCount, map.get(maxSum));
25         
26         return maxSum;
27     }
28     
29     private int[] getMostSum() {
30         List<Integer> list = new ArrayList<Integer>();
31         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
32             if (entry.getValue() == mostCount)
33                 list.add(entry.getKey());
34         }
35         return list.parallelStream().mapToInt(Integer::intValue).toArray();
36     }
37 }
原文地址:https://www.cnblogs.com/amazingzoe/p/6411596.html