当前位置:网站首页>[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);
}
边栏推荐
- Go從入門到實戰——接口(筆記)
- Go from introduction to practice - Interface (notes)
- SQL必需掌握的100个重要知识点:用通配符进行过滤
- Full record of 2022 open source moment at Huawei partners and Developers Conference
- 01-Golang-环境搭建
- Go from introduction to actual combat -- channel closing and broadcasting (notes)
- 关于异常处理的知识整理
- TypeScript学习
- 动态刷新mapper看过来
- 如何将队列里面的内容没秒钟执行一次优先级
猜你喜欢
随机推荐
Go从入门到实战——错误机制(笔记)
Go从入门到实战——Context与任务取消(笔记)
空指针异常
100 important knowledge points that SQL must master: sorting and retrieving data
让马化腾失望了!Web3.0,毫无希望
SQL server for circular usage
OpenSSL 编程 二:搭建 CA
分享|智慧环保-生态文明信息化解决方案(附PDF)
win11桌面出现“了解此图片”如何删除
Go从入门到实战——仅执行一次(笔记)
SQL必需掌握的100个重要知识点:检索数据
Quick excel export
Go从入门到实战——依赖管理(笔记)
安装gatewayworker之后启动start.php
神奇的POI读取excel模板文件报错
互联网 35~40 岁的一线研发人员,对于此岗位的核心竞争力是什么?
Oracle migration MySQL unique index case insensitive don't be afraid
STM32CubeIDE1.9.0\STM32CubeMX 6.5 F429IGT6加LAN8720A,配置ETH+LWIP
qt 大文件生成md5校验码
Go从入门到实战——共享内存并发机制(笔记)









