508. Most Frequent Subtree Sum

来源:互联网 发布:淘宝网家纺四件套 编辑:程序博客网 时间:2024/05/22 07:04

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.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int[] findFrequentTreeSum(TreeNode root) {        Map<Integer, Integer> data = new HashMap<Integer, Integer>();help(data, root);int max = Integer.MIN_VALUE;List<Integer> re = new ArrayList<>();for (Integer i : data.keySet()) {int n = data.get(i);if (n > max) {List<Integer> temp = new ArrayList<>();temp.add(i);max = n;re = temp;} else if (n == max)re.add(i);}int[] r = new int[re.size()];for (int i = 0; i < r.length; ++i)r[i] = re.get(i);return r;    }    static int help(Map<Integer, Integer> data, TreeNode root) {if (root == null)return 0;int val = root.val + help(data, root.left) + help(data, root.right);if (data.containsKey(val))data.put(val, data.get(val) + 1);elsedata.put(val, 1);return val;}}


0 0
原创粉丝点击