【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;
    }
}
相关推荐
Meteor_cyx14 小时前
Day12 二叉树遍历
算法
加藤不太惠15 小时前
十大排序其六
算法·排序算法
前端小刘哥15 小时前
视频推拉流平台EasyDSS技术特点及多元应用场景剖析
算法
Brianna Home15 小时前
从零到一:用Godot打造2D游戏《丛林探险》
算法·游戏·性能优化·游戏引擎·bug·godot·动画
小欣加油15 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
courniche15 小时前
ECDH、ECDHE、ECDLP、ECDSA傻傻分不清?
算法·密码学
前端小刘哥16 小时前
超低延迟与高并发:视频直播点播平台EasyDSS在游戏直播场景的技术实践
算法
毅炼16 小时前
常见排序算法
java·算法·排序算法
猫梦www16 小时前
力扣21:合并两个有序链表
数据结构·算法·leetcode·链表·golang·力扣
Han.miracle16 小时前
数据结构——排序的学习(一)
java·数据结构·学习·算法·排序算法