当前位置:网站首页>[LeetCode]515. 在每个树行中找最大值
[LeetCode]515. 在每个树行中找最大值
2022-06-27 19:35:00 【阿飞算法】
题目
515. 在每个树行中找最大值
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
方法1:层序遍历
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
int t = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();
t = Math.max(t, cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
res.add(t);
}
return res;
}
方法2:DFS
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
dfs(root, 0, res);
return res;
}
//depth表当前处理的节点的深度
private void dfs(TreeNode root, int depth, List<Integer> res) {
if (depth == res.size()) {
//第一次来到该深度的节点
res.add(root.val);
} else {
//非第一次来到该层
res.set(depth, Math.max(root.val, res.get(depth)));
}
if (root.left != null) dfs(root.left, depth + 1, res);
if (root.right != null) dfs(root.right, depth + 1, res);
}
边栏推荐
- JVM memory structure when creating objects
- Special training of guessing game
- 跟我一起AQS SOS AQS
- 100 important knowledge points that SQL must master: using functions to process data
- Go from introduction to actual combat - package (notes)
- Prospects for enterprise digitalization (38/100)
- 富文本 考试 填空题
- win11桌面出現“了解此圖片”如何删除
- 01-Golang-环境搭建
- 语言弱点列表--CWE,一个值得学习的网站
猜你喜欢

How to delete "know this picture" on win11 desktop

洛谷P5706 再分肥宅水

SQL必需掌握的100个重要知识点:排序检索数据

Set code exercise

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

Go from starting to Real - Interface (note)

Kirin V10 installation font

Go从入门到实战——Panic和recover(笔记)

Go从入门到实战——package(笔记)

猜拳游戏专题训练
随机推荐
Process control task
qt 大文件生成md5校验码
100 important knowledge points for SQL: in operator
于文文、胡夏等明星带你玩转派对 皮皮APP点燃你的夏日
分享|智慧环保-生态文明信息化解决方案(附PDF)
Acwing周赛57-最长连续子序列-(二分or树状数组)
SQL必需掌握的100个重要知识点:IN 操作符
Go从入门到实战——Context与任务取消(笔记)
100 important knowledge points that SQL must master: sorting and retrieving data
Codeforces Round #721 (Div. 2)
How to delete "know this picture" on win11 desktop
ARCS模型介绍
Go从入门到实战——package(笔记)
请教CMS小程序首页的幻灯片在哪里设置?
A set of system to reduce 10 times the traffic pressure in crowded areas
Modify large online games through CE modifier
Null pointer exception
gomock mockgen : unknown embedded interface
Go从入门到实战—— 多路选择和超时控制(笔记)
AI 绘画极简教程