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 -3return [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
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- 508. Most Frequent Subtree Sum
- Most Frequent Subtree Sum
- Most Frequent Subtree Sum
- Leetcode-508. Most Frequent Subtree Sum
- [leetcode] 508. Most Frequent Subtree Sum
- LeetCode 508. Most Frequent Subtree Sum
- Leetcode 508. Most Frequent Subtree Sum
- leetcode题解-508. Most Frequent Subtree Sum
- 正则表达式
- selenium+chromedriver安装及简单使用
- Problem--617A--Codeforces-- A. Elephant
- 用docker玩坏ubuntu虚拟机容器
- -bash: ./mysql_install_db: Permission denied
- 508. Most Frequent Subtree Sum
- 16年轻院赛后总结
- 算法导论第六章之最大、最小堆
- lintcode——二叉树的最小深度
- 控制器跳转和视图切换之NavigationController,UITabBarController,模态
- Gym100548H
- JavaScript深入之从原型到原型链
- excel文本提取
- -bash: pod: command not found