508. Most Frequent Subtree Sum

来源:互联网 发布:简易财务记账软件 编辑:程序博客网 时间:2024/05/02 02:14

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.

建立hashmap,存下来所有子树的subsum和subsum出现的次数count。之后用bucket sort找出出现次数最多的subsum。代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();    int count = 0;        public int[] findFrequentTreeSum(TreeNode root) {        int[] res = new int[0];        if (root == null) {            return res;        }        helper(root);        List<Integer>[] list = new List[count + 1];        for (int num: map.keySet()) {            int sumcount = map.get(num);            if (list[sumcount] == null) {                list[sumcount] = new ArrayList<Integer>();            }            list[sumcount].add(num);        }        for (int i = count; i >= 0; i --) {            if (list[i] != null) {                res = new int[list[i].size()];                for (int j = 0; j < list[i].size(); j ++) {                    res[j] = list[i].get(j);                }                break;            }        }        return res;    }        private int helper(TreeNode root) {        if (root == null) {            return 0;        }        int subsum = helper(root.left) + helper(root.right) + root.val;        map.put(subsum, map.getOrDefault(subsum, 0) + 1);        count ++;        return subsum;    }}

0 0
原创粉丝点击