当前位置:网站首页>[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;
}
边栏推荐
- 于文文、胡夏等明星带你玩转派对 皮皮APP点燃你的夏日
- uniapp拦截请求
- Acwing周赛57-数字操作-(思维+分解质因数)
- Go from introduction to actual combat - context and task cancellation (notes)
- 创建对象时JVM内存结构
- GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
- Go从入门到实战——任务的取消(笔记)
- Let Ma Huateng down! Web3.0, hopeless
- Method of reading file contents by Excel
- GBase 8a数据库用户密码安全相关参数汇总
猜你喜欢
随机推荐
快递e栈——数组篇小型项目
鲜为人知的mysql导入数据
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
Full record of 2022 open source moment at Huawei partners and Developers Conference
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
GBase 8a数据库用户密码安全相关参数汇总
Oracle migration MySQL unique index case insensitive don't be afraid
Bit. Store: long bear market, stable stacking products may become the main theme
洛谷P5706 再分肥宅水
Installing Oracle11g under Linux
JVM memory structure when creating objects
OpenSSL 编程 一:基本概念
Scrum和看板的区别
SQL必需掌握的100个重要知识点:过滤数据
[LeetCode]161. 相隔为 1 的编辑距离
Have time to look at ognl expressions
gomock mockgen : unknown embedded interface
100 important knowledge points that SQL must master: sorting and retrieving data
IO stream code









