【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;
    }
}
相关推荐
剪一朵云爱着5 小时前
力扣81. 搜索旋转排序数组 II
算法·leetcode·职场和发展
报错小能手7 小时前
刷题日常 5 二叉树最大深度
算法
Greedy Alg8 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER8 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油8 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
包饭厅咸鱼8 小时前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
无敌最俊朗@9 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^9 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
测试19989 小时前
Appium使用指南与自动化测试案例详解
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例