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 -3return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5 / \2 -5return [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
- 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
- 修改rc.local无法启动时自救
- Tooltip(提示框)组件
- Ajax理解及写法
- 获得电脑的sha1签名
- 直接插入排序的三种实现(c++)
- 508. Most Frequent Subtree Sum
- java——String类
- JQueryEasyUI 表单验证之验证框(非空验证)
- POJ 2386 Lake Counting
- basic algorithm in python
- Android中Service#onStartCommand方法的返回值
- Android广播机制二
- cpp——隐式转换——类类型
- 算法训练 字串统计