【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;
    }
}
相关推荐
Aaron15889 分钟前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
计算机安禾14 分钟前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
吃着火锅x唱着歌16 分钟前
LeetCode 150.逆波兰表达式求值
linux·算法·leetcode
YuanDaima204838 分钟前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法
阿Y加油吧44 分钟前
两道中等 DP 题拆解:打家劫舍 & 完全平方数
算法·leetcode·动态规划
七颗糖很甜1 小时前
python实现全国雷达拼图数据的SCIT风暴识别
python·算法·scipy
洌冰2 小时前
某车厂面试记录
面试·职场和发展
参.商.2 小时前
【Day49】236.二叉树的最近公共祖先
leetcode·golang
B325帅猫-量子前沿技术研究所2 小时前
PSD和FFT的关系
人工智能·算法
闻缺陷则喜何志丹2 小时前
【排序】P6149 [USACO20FEB] Triangles S|普及+
c++·算法·排序·洛谷