【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;
    }
}
相关推荐
积极向上的向日葵12 分钟前
有效的括号题解
数据结构·算法·
GIS小天17 分钟前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
_Itachi__39 分钟前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃39 分钟前
计算矩阵A和B的乘积
线性代数·算法·矩阵
不爱写代码的玉子43 分钟前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
Java 技术轻分享1 小时前
《树数据结构解析:核心概念、类型特性、应用场景及选择策略》
数据结构·算法·二叉树··都差速
芜湖xin1 小时前
【题解-洛谷】P1706 全排列问题
算法·dfs
chao_7892 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
曦月逸霜3 小时前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
每次的天空3 小时前
Android第十三次面试总结基础
android·面试·职场和发展