508. Most Frequent Subtree Sum
来源:互联网 发布:淘宝怎么免单 编辑:程序博客网 时间:2024/05/22 06:49
题目
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.
解答
public class Solution { HashMap<Integer,Integer> map = new HashMap<>(); int maxNum = 1; public int[] findFrequentTreeSum(TreeNode root) { if(root == null) return new int[0]; treeSum(root); ArrayList<Integer> list = new ArrayList<>(); for(Map.Entry<Integer,Integer> entry : map.entrySet()){ if(entry.getValue() == maxNum) list.add(entry.getKey()); } int[] res = new int[list.size()]; for(int i = 0; i < list.size(); i ++){ res[i] = list.get(i); } return res; } public int treeSum(TreeNode root){ int leftsum = (root.left == null) ? 0 : treeSum(root.left); int rightsum = (root.right == null) ? 0 : treeSum(root.right); int treeSum = root.val + leftsum + rightsum; map.put(treeSum, map.getOrDefault(treeSum,0) + 1); maxNum = Math.max(maxNum, map.get(treeSum)); return treeSum; }}算法思路:前序遍历,根、左子树、右子树,此根节点的和 = 根节点 + 左子树的和 + 右子树的和。就像求数组前n项的和一样,Sum(n) = Sum(n-1) + arr(n)。
代码分析:三目运算符优化代码;map.getOrDefault(key,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
- P1553 数字反转(升级版)
- vim commond
- 用Hugo搭建个人网站
- Java去掉字符串中所有的标签,获取纯文本内容
- 关于内存泄漏的一些知识概括和记录
- 508. Most Frequent Subtree Sum
- 文件及目录命令
- MediaPlayer播放应用中、内存卡中、网络中的音乐
- CSS实现的几款不错的菜单栏
- 【Python】学习笔记——-3.0、函数
- IO流_字符流的2种读数据的方式
- C语言的代码内存布局
- 来淄博旅游 (sdut oj)
- java线程状态