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.

题目含义:给一棵树,找出现次数最多的子树和。子树和就是一个结点以及它下方所有结点构成的子树的总和,在这些总和中找一个出现次数最多的结果,如果有很多个这样的结果,返回这些结果构成的数组

 1     private int maxCount = 0;
2 private Map<Integer,Integer> sumMap = new HashMap<>();
3 private int getNodeSum(TreeNode root) {
4 if (root == null) return 0;
5 int sum = root.val + getNodeSum(root.left) +getNodeSum(root.right);
6 int newCount = sumMap.getOrDefault(sum,0)+1;
7 sumMap.put(sum,newCount);
8 maxCount = Math.max(maxCount,newCount);
9 return sum;
10 }
11
12 public int[] findFrequentTreeSum(TreeNode root) {
13 getNodeSum(root);
14 List<Integer> sums = new ArrayList<>();
15 for (Map.Entry<Integer,Integer> entry:sumMap.entrySet())
16 {
17 if (entry.getValue() == maxCount)
18 sums.add(entry.getKey());
19 }
20 int[] result = new int[sums.size()];
21 for (int i=0;i<sums.size();i++)
22 {
23 result[i] = sums.get(i);
24 }
25 return result;
26 }

最新文章

  1. oracle 锁的介绍 (转)
  2. jQuery Vlidate 演示样例
  3. Socket 接收本地短连接并转发为长连接 多线程
  4. DB2 相关操作
  5. php添加gd
  6. 在linux下利用信号量实现一个写者线程多个读者线程
  7. linux发行版和内核的关系
  8. [SinGuLaRiTy] 组合数学题目复习
  9. HttpClient4登陆有验证码的网站
  10. 哪些 Python 库让你相见恨晚?【转】
  11. mvc4+entityFramework5 发布时遇到的纠结问题
  12. Linux 程序设计1:深入浅出 Linux 共享内存
  13. Python3 tkinter基础 Entry state 不可写 不可选 不可复制的输入框
  14. Win32汇编学习(4):绘制文本
  15. vue之v-if和v-show
  16. iOS 设置 UIWebView UserAgent
  17. mongodb MongoDB 聚合 group(转)
  18. Trove系列(八)——Trove的配置管理相关的功能介绍
  19. linux主机555、644、666、755、777权限详解
  20. linux系统中/etc/syslog.conf文件解读

热门文章

  1. tomcat启动报错There is insufficient memory for the Java Runtime Environment to continue
  2. c++设计模式概述之命令
  3. nim_duilib(13)之添加fmt库
  4. 【LeetCode】1410. 实体解析器 HTML Entity Parser HTML
  5. XSLT映射文件函数
  6. 主流的 API 架构
  7. 【环境搭建】安装pyQt5 在pycharm报This application failed to start because no Qt platform plugin could be initialized的问题
  8. 第二十三个知识点:写一个实现蒙哥马利算法的C程序
  9. &#39;real&#39;词频分析
  10. 更新系统为High sierra 后无法使用Cocoapods