【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 小时前
【LeetCode热题100(82/100)】单词拆分
算法·leetcode·职场和发展
mit6.8246 小时前
mysql exe
算法
2501_901147836 小时前
动态规划在整除子集问题中的应用与高性能实现分析
算法·职场和发展·动态规划
中草药z6 小时前
【嵌入模型】概念、应用与两大 AI 开源社区(Hugging Face / 魔塔)
人工智能·算法·机器学习·数据集·向量·嵌入模型
CCPC不拿奖不改名7 小时前
SQL基础(SQL小白教程):MySQL语句+环境一键搭建+面试习题
数据库·sql·计算机网络·mysql·oracle·面试·职场和发展
踩坑记录7 小时前
leetcode hot100 189.轮转数组 medium
leetcode
知乎的哥廷根数学学派7 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
ADI_OP7 小时前
ADAU1452的开发教程10:逻辑算法模块
算法·adi dsp中文资料·adi dsp·adi音频dsp·adi dsp开发教程·sigmadsp的开发详解
xingzhemengyou17 小时前
C语言 查找一个字符在字符串中第i次出现的位置
c语言·算法
Dream it possible!8 小时前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试