508. Most Frequent Subtree Sum

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     }
复制代码

 

posted @   daniel456  阅读(132)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示