当前位置:网站首页>[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;
}
边栏推荐
- AI 绘画极简教程
- C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
- GBase 8a数据库用户密码安全相关参数汇总
- Go从入门到实战——多态(笔记)
- Quick excel export according to customized excel Title Template
- Codeforces Global Round 14
- GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
- Let Ma Huateng down! Web3.0, hopeless
- GBase 8a OLAP分析函数cume_dist的使用样例
- AI painting minimalist tutorial
猜你喜欢

Go从入门到实战——行为的定义和实现(笔记)

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

Express e stack - small items in array

100 important knowledge points that SQL must master: sorting and retrieving data

∫(0→1) ln(1+x) / (x ² + 1) dx

Go from introduction to actual combat -- channel closing and broadcasting (notes)

DO280OpenShift访问控制--security policy和章节实验

.NET学习笔记(五)----Lambda、Linq、匿名类(var)、扩展方法

JVM memory structure when creating objects

快递e栈——数组篇小型项目
随机推荐
Go from introduction to practice - Interface (notes)
Codeforces Round #721 (Div. 2)
matlab查找某一行或者某一列在矩阵中的位置
农产品期货怎么做怎么开户,期货开户手续费多少,找谁能优惠手续费?
gomock mockgen : unknown embedded interface
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
抖音的兴趣电商已经碰到流量天花板?
TreeSet details
100 important knowledge points for SQL: in operator
SQL必需掌握的100个重要知识点:创建计算字段
IO stream code
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
快递e栈——数组篇小型项目
linux下安装oracle11g 静默安装教程
专题教程——选队长游戏
Go从入门到实战——仅需任意任务完成(笔记)
Bit. Store: long bear market, stable stacking products may become the main theme
图解基于AQS队列实现的CountDownLatch和CyclicBarrier
Go from entry to practice -- CSP concurrency mechanism (note)
创建对象时JVM内存结构