当前位置:网站首页>力扣 515. 在每个树行中找最大值
力扣 515. 在每个树行中找最大值
2022-06-26 03:53:00 【冷酷的摸鱼小将】
题目
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例

输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
输入: root = [1,2,3]
输出: [1,3]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:队列
Java实现
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int sz = q.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
max = cur.val > max ? cur.val : max;
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
res.add(max);
}
return res;
}
}

边栏推荐
- MySQL高級篇第一章(linux下安裝MySQL)【下】
- 【LOJ#6718】九个太阳「弱」化版(循环卷积,任意模数NTT)
- IEDA 突然找不到了compact middle packages
- 链路监控 pinpoint
- Use soapUI to access the corresponding ESB project
- What does virtualization mean? What technologies are included? What is the difference with private cloud?
- General operations of asynctask
- 优化——多目标规划
- [collection of good books] from technology to products
- "Renegotiation" agreement
猜你喜欢

1.基础关

The kotlin project is running normally and the R file cannot be found

Evaluation - analytic hierarchy process

(15) Blender source code analysis flash window display menu function

如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup

【Flink】Flink Sort-Shuffle写流程简析

"Renegotiation" agreement

EF core Basics

Use soapUI to access the corresponding ESB project

Quanergy welcomes Lori sundberg as chief human resources officer
随机推荐
2022.6.20-----leetcode.715
Camera-CreateCaptureSession
MySQL stored procedure
【MySQL】 MySQL 导出数据库
I/o virtualization technology - vfio
MySQL advanced Chapter 1 (installing MySQL under Linux) [2]
xml 解析bean工具类
QPS的概念和实现
2020 summary: industrial software development under Internet thinking
Ieda suddenly cannot find compact middle packages
IEDA 突然找不到了compact middle packages
. Net core learning journey
Small record of neural network learning 71 - tensorflow2 deep learning with Google Lab
763. 划分字母区间
Camera-CreateCaptureSession
Evaluation - analytic hierarchy process
优化——多目标规划
Introduction of mybatis invalid
Navicat16 wireless trial
Mybatis的引入问题invalid