【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;
    }
}
相关推荐
AI备案指南-满满2 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
土司大王3 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背4 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
测试19984 小时前
Selenium 无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
zander2585 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲5 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力555 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜5 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者5 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法