【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;
    }
}
相关推荐
Physicist in Geophy.3 小时前
一维波动方程(从变分法角度)
线性代数·算法·机器学习
im_AMBER3 小时前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
Liue612312313 小时前
【YOLO11】基于C2CGA算法的金属零件涂胶缺陷检测与分类
人工智能·算法·分类
!!!!8133 小时前
蓝桥备赛Day1
数据结构·算法
Mr_Xuhhh3 小时前
介绍一下ref
开发语言·c++·算法
夏鹏今天学习了吗3 小时前
【LeetCode热题100(99/100)】柱状图中最大的矩形
算法·leetcode·职场和发展
啊阿狸不会拉杆3 小时前
《机器学习导论》第 9 章-决策树
人工智能·python·算法·决策树·机器学习·数据挖掘·剪枝
Mr_Xuhhh3 小时前
C++11实现线程池
开发语言·c++·算法
若水不如远方3 小时前
分布式一致性(三):共识的黎明——Quorum 机制与 Basic Paxos
分布式·后端·算法
only-qi3 小时前
leetcode24两两交换链表中的节点 快慢指针实现
数据结构·算法·链表