当前位置:网站首页>[LeetCode]508. 出現次數最多的子樹元素和
[LeetCode]508. 出現次數最多的子樹元素和
2022-06-27 21:49:00 【阿飛算法】
題目
508. 出現次數最多的子樹元素和
給你一個二叉樹的根結點 root ,請返回出現次數最多的子樹元素和。如果有多個元素出現的次數相同,返回所有出現次數最多的子樹元素和(不限順序)。
一個結點的 「子樹元素和」 定義為以該結點為根的二叉樹上所有結點的元素之和(包括結點本身)。
示例 1:
輸入: root = [5,2,-3]
輸出: [2,-3,4]
示例 2:
輸入: root = [5,2,-5]
輸出: [2]
提示:
節點數在 [1, 104] 範圍內
-105 <= Node.val <= 105
方法1:DFS
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) return new int[]{
};
dfs(root);
List<Integer> list = new ArrayList<>();
for (int k : map.keySet()) {
if (map.get(k) == maxx) list.add(k);
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) res[i] = list.get(i);
return res;
}
int maxx = 0;//出現的最大的次數
//記錄當前出現的sum 的次數
Map<Integer, Integer> map = new HashMap<>();
private int dfs(TreeNode root) {
if (root == null) return 0;
int l = dfs(root.left);
int r = dfs(root.right);
int s = l + root.val + r;
map.put(s, map.getOrDefault(s, 0) + 1);
maxx = Math.max(maxx, map.get(s));
return s;
}
边栏推荐
猜你喜欢

SQL必需掌握的100个重要知识点:使用函数处理数据

图解基于AQS队列实现的CountDownLatch和CyclicBarrier

Go从入门到实战——CSP并发机制(笔记)

100 important knowledge points that SQL must master: filtering data

Use the storcli tool to configure raid. Just collect this article

STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP

win11桌面出现“了解此图片”如何删除

Let Ma Huateng down! Web3.0, hopeless

How to participate in openharmony code contribution

开源技术交流丨一站式全自动化运维管家ChengYing入门介绍
随机推荐
Tiktok's interest in e-commerce has hit the traffic ceiling?
豆沙绿保护你的双眼
ABC-Teleporter Setting-(思维+最短路)
抖音的兴趣电商已经碰到流量天花板?
C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
Quick excel export
创建对象时JVM内存结构
MySQL client tools are recommended. I can't imagine that it is best to use Juran
Use the storcli tool to configure raid. Just collect this article
Save method of JPA stepping pit series
Go 访问GBase 8a 数据库的一个方法
At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
Go from introduction to practice - polymorphism (note)
win11桌面出现“了解此图片”如何删除
GBase 8a OLAP分析函数 cume_dist的使用样例
Prospects for enterprise digitalization (38/100)
Special tutorial - Captain selection game
100 important knowledge points for SQL: in operator
SQL必需掌握的100个重要知识点:过滤数据
Quick excel export according to customized excel Title Template