[LeetCode 508] Most Frequent Subtree Sum (Medium)

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.

Solution

  1. 要得到每个subtree的sum,那么就需要用post-order自下而上遍历。
  2. 同时要用一个map来记录,每个subsum出现的次数;并且需要记录当前最高出现的频次。
  3. 用recursive来做,每次得到一个subsum都要向map中累计其出现的频次。
    -- 如果该频次==最高频次, 向结果中加入该subsum
    -- 如果该频次>最高频次, 说明之前结果中记录的subsum已经不是highest frequency了,那么结果集需要先清空,然后再记录当前频次; 更新最高出现频次。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] findFrequentTreeSum(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        
        Map  sumsMap = new HashMap <> ();
        int [] highestFrequency = { 0 };
        List result = new ArrayList <> ();
        
        findFrequentTreeSum (root, sumsMap, highestFrequency, result);
        
        System.out.println (result.toString());
        
        int[] res = new int[result.size()];
        int i = 0;
        for (int entry : result) {
            res [i++] = entry;
        }
        
        return  res;
    }
    
    private int findFrequentTreeSum (TreeNode root, 
                                     Map  sumsMap, 
                                     int [] highestFrequency, 
                                     List  result) {
        int sum = 0;
        if (root.left != null) {
            sum += findFrequentTreeSum (root.left, sumsMap, highestFrequency, result);
        }
        
        if (root.right != null) {
            sum += findFrequentTreeSum (root.right, sumsMap, highestFrequency, result);
        }
        
        sum += root.val;
        sumsMap.put (sum, sumsMap.getOrDefault (sum, 0) + 1);
        
        if (sumsMap.get (sum) > highestFrequency [0]) {
            result.clear ();
            highestFrequency [0] = sumsMap.get (sum);
            result.add (sum);
        } else if (sumsMap.get (sum) == highestFrequency [0]) {
            result.add (sum);
        }
        
        return sum;
    }
}

你可能感兴趣的:([LeetCode 508] Most Frequent Subtree Sum (Medium))