当前位置:网站首页>[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;
}
边栏推荐
- ABC-Teleporter Setting-(思维+最短路)
- Installing Oracle11g under Linux
- Xiao Wang's interview training task
- TreeSet details
- [LeetCode]515. 在每个树行中找最大值
- Codeforces Round #716 (Div. 2)
- oracle迁移mysql唯一索引大小写不区分别怕
- 语言弱点列表--CWE,一个值得学习的网站
- 100 important knowledge points that SQL must master: sorting and retrieving data
- 洛谷P5706 再分肥宅水
猜你喜欢

Full record of 2022 open source moment at Huawei partners and Developers Conference

猜拳游戏专题训练

Go從入門到實戰——接口(筆記)

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

Go from introduction to actual combat - panic and recover (notes)

让马化腾失望了!Web3.0,毫无希望

Process control task

"Apprendre cette image" apparaît sur le Bureau win11 comment supprimer

空指针异常

Go from introduction to practice - Interface (notes)
随机推荐
Go从入门到实战——共享内存并发机制(笔记)
Prospects for enterprise digitalization (38/100)
互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?
qt 大文件生成md5校验码
Go从入门到实战——channel的关闭和广播(笔记)
Bit.Store:熊市漫漫,稳定Staking产品或成主旋律
The difference between scrum and Kanban
Save method of JPA stepping pit series
关于异常处理的知识整理
GBase 8a数据库用户密码安全相关参数汇总
MySQL client tools are recommended. I can't imagine that it is best to use Juran
100 important knowledge points that SQL must master: retrieving data
Go从入门到实战——错误机制(笔记)
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
Go从入门到实战——协程机制(笔记)
Codeforces Round #719 (Div. 3)
Array assignment
Go from entry to practice -- CSP concurrency mechanism (note)
Magic POI error in reading excel template file