当前位置:网站首页>[LeetCode]508. 出现次数最多的子树元素和
[LeetCode]508. 出现次数最多的子树元素和
2022-06-27 19:35: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;
}
边栏推荐
- Knowledge sorting of exception handling
- MySQL client tools are recommended. I can't imagine that it is best to use Juran
- Codeforces Round #721 (Div. 2)
- Let Ma Huateng down! Web3.0, hopeless
- SQL必需掌握的100个重要知识点:过滤数据
- 流程控制任务
- 猜拳游戏专题训练
- CEPH distributed storage
- TreeSet详解
- 100 important knowledge points that SQL must master: creating calculation fields
猜你喜欢

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

CORBA 架构体系指南(通用对象请求代理体系架构)

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

富文本 考试 填空题

Set code exercise

Go from introduction to practice -- coordination mechanism (note)

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

Go from entry to practice -- CSP concurrency mechanism (note)

Kirin V10 installation font

Let Ma Huateng down! Web3.0, hopeless
随机推荐
100 important knowledge points for SQL: in operator
win11桌面出現“了解此圖片”如何删除
Codeforces Round #719 (Div. 3)
让马化腾失望了!Web3.0,毫无希望
Go从入门到实战——channel的关闭和广播(笔记)
GBase 8a OLAP函数group by grouping sets的使用样例
猜拳游戏专题训练
豆沙绿保护你的双眼
Express e stack - small items in array
100 important knowledge points that SQL must master: filtering data
Go from introduction to actual combat - package (notes)
Go from entry to practice - multiple selection and timeout control (notes)
oracle迁移mysql唯一索引大小写不区分别怕
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
White whoring red team goby & POC, how do you call white whoring?
SQL必需掌握的100个重要知识点:创建计算字段
GBase 8a OLAP分析函数cume_dist的使用样例
VMware vSphere esxi 7.0 installation tutorial
io流代码
Go from starting to Real - Interface (note)