【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;
    }
}
相关推荐
Not Dr.Wang42229 分钟前
自动控制系统稳定性研究及判据分析
算法
VT.馒头30 分钟前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
ffqws_35 分钟前
A*算法:P5507 机关 题解
算法
执着2591 小时前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
2501_901147831 小时前
学习笔记:单调递增数字求解的迭代优化与工程实践
linux·服务器·笔记·学习·算法
AI科技星1 小时前
张祥前统一场论核心场方程的经典验证-基于电子与质子的求导溯源及力的精确计算
线性代数·算法·机器学习·矩阵·概率论
kebijuelun1 小时前
ERNIE 5.0:统一自回归多模态与弹性训练
人工智能·算法·语言模型·transformer
历程里程碑1 小时前
普通数组----最大子数组和
大数据·算法·elasticsearch·搜索引擎·排序算法·哈希算法·散列表
52Hz1182 小时前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode