【LeetCode-中等题】515. 在每个树行中找最大值

文章目录

题目

方法一:二叉树的层序遍历每一层求最大值max

本题解题过程大体思路和二叉树的层序遍历没有什么不同

java 复制代码
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        
           List<Integer> res = new ArrayList<>();
           if(root == null) return res;
           Deque<TreeNode> queue = new LinkedList<>();
           queue.offer(root);
           int rootmax = 0;
           while(!queue.isEmpty()){
               int size = queue.size();
               rootmax = Integer.MIN_VALUE;
               for(int i = 0 ; i < size ; i++){
                   root = queue.poll();
                   rootmax = Math.max(rootmax,root.val);//取每一层的最大值
                   if(root.left!=null) queue.offer(root.left);
                   if(root.right!=null) queue.offer(root.right);
               }
               res.add(rootmax);//将每一层的最大值加入结果集
           }
        return res;
    }
}
相关推荐
pchmi6 分钟前
C#快速幂算法
算法·c#
AAIshangyanxiu6 分钟前
基于ArcGIS Pro、Python、USLE、INVEST模型等多技术融合的生态系统服务构建生态安全格局
python·算法·arcgis pro·invest模型·生态安全格局·usle
OKkankan1 小时前
排序(数据结构)
c语言·数据结构·c++·算法
m0_663234014 小时前
Rust并发编程实践:10分钟入门系统级编程
python·算法·rust
zdsji4 小时前
如何制作安装包打包软件
算法·rust·vue
糖葫芦君5 小时前
TD时间差分算法
人工智能·算法
Ronin-Lotus6 小时前
嵌入式硬件篇---常用的汇编语言指令
单片机·嵌入式硬件·职场和发展·c·汇编语言
没明白白8 小时前
插入排序:一种简单而直观的排序算法
java·算法·排序算法
程序员南飞8 小时前
算法-数据结构-图的构建(邻接矩阵表示)
java·数据结构·算法·职场和发展
指掀涛澜天下惊8 小时前
DirectX12(D3D12)基础教程三 线性代数与3D世界空间
线性代数·算法·机器学习·3d