栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

二叉树每层的最大值java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树每层的最大值java实现

class Solution {
    public List largestValues(TreeNode root) {
        //为了避免队列中的节点混淆,分别使用两个计数器来记录当前队列中当前层节点的个数和下一层节点的个数
        int current = 0;
        int next = 0;
        Queue queue = new linkedList<>();
        int max = Integer.MIN_VALUE;
        if(root != null){
            queue.offer(root);
            current = 1;
        }
        //使用动态数组来存储结果
        ArrayList result = new ArrayList<>();
        //层次遍历二叉树
        while(!queue.isEmpty()){
            //遍历每一层的节点遍历时需要减去当前成的计数器,计入子节点时需要加上下一层节点的个数
            TreeNode node = queue.poll();
            if(max < node.val){
                max = node.val;
            }
            current--;
            if(node.left != null){
                queue.offer(node.left);
                next++;
            }
            if(node.right != null){
                queue.offer(node.right);
                next++;
            }
            //m当每层遍历结束时需要对计数器和结果重新处理
            if(current == 0){
                current = next;
                next = 0;
                result.add(max);
                max = Integer.MIN_VALUE;
            }
        }
        return result;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572388.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号