当前位置:网站首页>LeetCode.515. 在每个树行中找最大值___逐一BFS+DFS+按层BFS
LeetCode.515. 在每个树行中找最大值___逐一BFS+DFS+按层BFS
2022-07-01 10:42: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
Solution1( 逐一BFS ):
- 首先我们采取最朴素的解法,即我们要找的是二叉树中每一层的最大值,显然我们可以使用广搜遍历二叉树,对每一层的元素进行逐个取出,并始终维护一个最大值,同时取出元素后还要将其左右非空子元素放进队列尾部。
这里我们在进行逐一BFS时是如何辨别该元素是哪一层的呢?
我们使用自定义类State来实现,即可维护每一个节点元素的深度。
Code1:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
// 逐一BFS
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = bfs(root);
return res;
}
public List<Integer> bfs(TreeNode root){
Queue<State> queue = new LinkedList<State>();
if(root == null){
return new ArrayList<Integer>();
}
State start = new State(root,0);
queue.offer(start);
List<Integer> list = new ArrayList<>();
State max_thisDepth = new State(new TreeNode(Integer.MIN_VALUE,null,null),0);
while(queue.size()!=0){
TreeNode temp = queue.peek().node;
int now_depth = queue.peek().depth;
if(temp.left != null){
queue.offer(new State(temp.left,now_depth + 1));
}
if(temp.right != null){
queue.offer(new State(temp.right,now_depth + 1));
}
State thisState = queue.poll();
TreeNode thisNode = thisState.node;
if(max_thisDepth.depth == thisState.depth){
max_thisDepth.node.val = Math.max(max_thisDepth.node.val,thisNode.val);
}
else{
list.add(max_thisDepth.node.val);
max_thisDepth.node.val = thisNode.val;
max_thisDepth.depth = thisState.depth;
}
}
list.add(max_thisDepth.node.val);
return list;
}
}
class State{
TreeNode node;
int depth;
public State(TreeNode node,int depth){
this.node = node;
this.depth = depth;
}
}
Solution2( DFS ):
- 按照该题的情景是应该使用广搜的,但是使用深搜同样可以解决,我们只要搭配一个
哈希表进行记录每一层的最大值即可,这样在遍历二叉树的时候我们只要根据此时遍历节点的深度对哈希表进行实时更新即可。
Code2:
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public List<Integer> largestValues(TreeNode root) {
if(root == null){
return new ArrayList<>();
}
dfs(root,0);
List<Integer> res = new ArrayList<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
res.add(entry.getValue());
}
return res;
}
public void dfs(TreeNode root,int depth){
if(map.containsKey(depth)){
int value = map.get(depth);
if(root.val > value){
map.put(depth,root.val);
}
}
else{
map.put(depth,root.val);
}
if(root.left!=null){
dfs(root.left,depth+1);
}
if(root.right!=null){
dfs(root.right,depth+1);
}
return;
}
}
Solution3( 按层BFS ):
- 对于方法一的广搜,我们可以对其进行优化,即不用实时的对每个节点都维护一个深度;
- 由于我们只要求每层的最大值,我们可以按照
一层一层来进行遍历,即每次我们先从队列中取出该层的所有元素,再对其进行一个遍历即可,由于我们每次取出的都是同一层的元素,因此是不需要考虑深度问题,因此可以化繁为简;
在实现方面,我们只需要遍历时根据初始队列的长度len,从队列中取出前len个元素,即可达到取出该层的所有元素,且在取出元素的同时我们也不要忘记将取出的元素的左右非空元素再放入队列即可,这样即可达到每次队列内的元素都是同一层的元素,因此这样可以起到按层来进行搜索的效果。
Code3:
class Solution {
public List<Integer> largestValues(TreeNode root) {
if(root == null){
return new ArrayList<>();
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
List<Integer> res = new ArrayList<>();
while(!queue.isEmpty()){
int this_depth_len = queue.size();
int max = Integer.MIN_VALUE;
while(this_depth_len != 0){
//把该层都取出
TreeNode temp = queue.poll();
max = Math.max(temp.val,max);
if(temp.left != null)
queue.offer(temp.left);
if(temp.right != null)
queue.offer(temp.right);
this_depth_len--;
}
res.add(max);
}
return res;
}
}
边栏推荐
- JD and Tencent renewed the three-year strategic cooperation agreement; The starting salary rose to 260000 yuan! Samsung sk of South Korea competes for salary increase to retain semiconductor talents;
- leetcode:111. Minimum depth of binary tree
- How to get the maximum value of column two and regenerate the table when the SQL Server column one is the same
- 使用强大的DBPack处理分布式事务(PHP使用教程)
- 零基础入门测试该学什么?最全整理,照着学就对了
- The exclusive collection of China lunar exploration project is limited to sale!
- Handling distributed transactions with powerful dbpack (PHP tutorial)
- Crawler (2) - requests (1) | deep parsing of requests module
- 华为HMS Core携手超图为三维GIS注入新动能
- Project0: Games
猜你喜欢

北汽蓝谷:业绩承压,极狐难期

Introduction of uniapp wechat applet components on demand

Matplotlib data visualization Foundation

数字藏品平台搭建需要注意哪些法律风险及资质?

Venv: directory structure of venv

2022年已经过去一半了,是不是很突然呢?

What if the win11 account is locked and unable to log in? Win11 account is locked and unable to log in

C# 一行代码计算文件的MD5值 - CodePlus系列

.NET 5.0+ 无需依赖第三方 原生实现定时任务

SQL SERVER2014删除数据库失败,报错偏移量0x0000...
随机推荐
爬虫(2) - Requests(1) | Requests模块的深度解析
[encounter Django] - (II) database configuration
Infinite innovation in cloud "vision" | the 2022 Alibaba cloud live summit was officially launched
Today in history: the semiconductor war in the late 1990s; Von Neumann published the first draft; CBS acquires CNET
缺少比较器,运放来救场!(运放当做比较器电路记录)
TC8:UDP_ USER_ INTERFACE_ 01-08
有大佬知道这是为啥吗?表结构都是刚直接复制的源表 mysql-cdc
The list of winners of the digital collection of "century master" was announced
prism journal导航按钮的可用性探索记录
IDEA运行报错Command line is too long. Shorten command line for...
新一代云原生数据库的设计与实践
选择在中金证券上炒股开户可以吗?安全吗?
Kotlin 协程调度切换线程是时候解开真相了
Error: missing revert data in call exception
Who's still buying three squirrels
数字藏品平台搭建需要注意哪些法律风险及资质?
[.NET6]使用ML.NET+ONNX预训练模型整活B站经典《华强买瓜》
Introduction of uniapp wechat applet components on demand
日本教授起诉英特尔FPGA与SoC产品侵犯一项设计专利
12款大家都在用的产品管理平台