【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;
    }
}
相关推荐
Fly Wine1 小时前
Leetcode之有效字母异位词
算法·leetcode·职场和发展
程序员夏末3 小时前
【LeetCode | 第七篇】算法笔记
笔记·算法·leetcode
csdn_aspnet3 小时前
C/C++ 两个凸多边形之间的切线(Tangents between two Convex Polygons)
c语言·c++·算法
数据皮皮侠4 小时前
中国城市间地理距离矩阵(2024)
大数据·数据库·人工智能·算法·制造
3GPP仿真实验室4 小时前
深度解析基站接收机核心算法:从 MRC 到 IRC 的空间滤波演进
算法
Boop_wu4 小时前
[Java 算法] 动态规划(1)
算法·动态规划
WolfGang0073214 小时前
代码随想录算法训练营 Day18 | 二叉树 part08
算法
hanlin035 小时前
刷题笔记:力扣第43、67题(字符串计算)
笔记·算法·leetcode
yang_B6215 小时前
最小二乘法 拟合平面
算法·平面·最小二乘法
放下华子我只抽RuiKe55 小时前
深度学习全景指南:硬核实战版
人工智能·深度学习·神经网络·算法·机器学习·自然语言处理·数据挖掘