【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;
    }
}
相关推荐
无敌昊哥战神10 小时前
【LeetCode 134】加油站:图解指针跳跃与 O(N) 极简贪心,避开 Python 隐藏坑!
c语言·python·算法·leetcode
人道领域10 小时前
【LeetCode刷题日记】222.极速计算完全二叉树节点数:O(log²n)算法揭秘
java·数据结构·算法·leetcode·深度优先
目黑live +wacyltd10 小时前
算法备案的实操指南(含截图示例)
人工智能·算法·llm·大模型备案·算法备案
小糯米60110 小时前
C语言 指针4
c语言·数据结构·算法
略知java的景初10 小时前
【面试特集】JVM 内存与对象
jvm·面试·职场和发展
洛水水10 小时前
【力扣100题】36.二叉树展开为链表
算法·leetcode·链表
lwf00616410 小时前
PNN (Product-based Neural Network) 学习日记
算法·机器学习
ZPC821010 小时前
YOLO-3D + 双目相机 (RGB + 深度 + 点云) → 3D 位置 + 抓取姿态
人工智能·算法·计算机视觉·机器人
ZPC821010 小时前
YOLOv8-3D(3D 目标检测 + 6D 抓取姿态)
算法·机器人
bubiyoushang88810 小时前
基于 TGLVM 算法的迁移学习分类系统
算法·分类·迁移学习