二叉树的层序遍历

news2024/9/23 9:30:22

二叉树的层序遍历


层序遍历一个二叉树。就是从左到右一层一层的去遍历二叉树。

需要借用一个辅助数据结构即队列来实现,队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。

而这种层序遍历方式就是图论中的广度优先遍历,只不过我们应用在二叉树上。

使用队列实现二叉树广度优先遍历,动画如下:
在这里插入图片描述
代码:
力扣题目:102.二叉树的层序遍历

class Solution {
    public List<List<Integer>> resList = new ArrayList<List<Integer>>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        //checkFun01(root,0);
        checkFun02(root);

        return resList;
    }

    //DFS--递归方式
    public void checkFun01(TreeNode node, Integer deep) {
        if (node == null) return;
        deep++;

        if (resList.size() < deep) {
            //当层级增加时,list的Item也增加,利用list的索引值进行层级界定
            List<Integer> item = new ArrayList<Integer>();
            resList.add(item);
        }
        resList.get(deep - 1).add(node.val);

        checkFun01(node.left, deep);
        checkFun01(node.right, deep);
    }

    //BFS--迭代方式--借助队列
    public void checkFun02(TreeNode node) {
        if (node == null) return;
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        que.offer(node);

        while (!que.isEmpty()) {
            List<Integer> itemList = new ArrayList<Integer>();
            int len = que.size();

            while (len > 0) {
                TreeNode tmpNode = que.poll();
                itemList.add(tmpNode.val);

                if (tmpNode.left != null) que.offer(tmpNode.left);
                if (tmpNode.right != null) que.offer(tmpNode.right);
                len--;
            }

            resList.add(itemList);
        }

    }
}

力扣题目:二叉树的层次遍历 II

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();

        if(root == null){
            return list;
        }
        que.offerLast(root);
       while (!que.isEmpty()) {
            List<Integer> levelList = new ArrayList<>();

            int levelSize = que.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode peek = que.peekFirst();
                levelList.add(que.pollFirst().val);

                if (peek.left != null) {
                    que.offerLast(peek.left);
                }
                if (peek.right != null) {
                    que.offerLast(peek.right);
                }
            }
            list.add(levelList);
        }

        List<List<Integer>> result = new ArrayList<>();
        for (int i = list.size() - 1; i >= 0; i-- ) {
            result.add(list.get(i));
        }

        return result;
    }
}

力扣题目:199. 二叉树的右视图

//解法一:递归
/**
 * 解法:队列,迭代。
 * 每次返回每层的最后一个字段即可。
 */
 public List<Integer> rightSideView(TreeNode root) {
     List<Integer> list = new ArrayList<>();
     Deque<TreeNode> que = new LinkedList<>();

     if (root == null) {
          return list;
      }

      que.offerLast(root);
      while (!que.isEmpty()) {
          int levelSize = que.size();

          for (int i = 0; i < levelSize; i++) {
              TreeNode poll = que.pollFirst();

              if (poll.left != null) {
                  que.addLast(poll.left);
              }
              if (poll.right != null) {
                  que.addLast(poll.right);
              }

              if (i == levelSize - 1) {
                  list.add(poll.val);
              }
          }
      }

      return list;
  }
} 


//小优化:每层右孩子先入队。
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    Deque<TreeNode> que = new LinkedList<>();

    if (root == null) {
        return list;
    }

    que.offerLast(root);

    while(!que.isEmpty()){
        int len = que.size();

        for (int i = 0; i < len; i++) {
            TreeNode poll = que.pollFirst();

            if (poll.right != null) {
                que.addLast(poll.right);
            }
            if (poll.left != null) {
                que.addLast(poll.left);
            }

            if (i == 0) {
                list.add(poll.val);
            }
        }
    }

    return list;
}

力扣题目:637. 二叉树的层平均值

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();
        
        if (root == null) {
            return list;
        }

        que.offerLast(root);
        while(!que.isEmpty()){
            int len = que.size();
            double sum = 0.0;

            for(int i = 0; i < len; i++){
                TreeNode poll = que.pollFirst();
                sum += poll.val;

                if (poll.left != null) {
                    que.addLast(poll.left);
                }
                if (poll.right != null) {
                    que.addLast(poll.right);
                }
            }
            list.add(sum / len);
        }
        return list;
    }
}

力扣题目:429. N 叉树的层序遍历

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> list = new ArrayList<>();
        Deque<Node> que = new LinkedList<>();

        if(root == null){
            return list;
        } 

        que.offerLast(root);
        while(!que.isEmpty()){
            int len = que.size();
            List<Integer> item = new ArrayList<>();

            for(int i = 0; i < len; i++){
                Node poll = que.pollFirst();
                item.add(poll.val);

                List<Node> children = poll.children;
                if (children == null || children.size() == 0) {
                    continue;
                }
                for (Node child : children) {
                    if (child != null) {
                        que.offerLast(child);
                    }
                }
            }

            list.add(item);
        }

        return list;
    }
}

力扣题目:515.在每个树行中找最大值

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> que = new LinkedList<>();

        if(root == null){
            return list;
        }

        que.offerLast(root);
        while(!que.isEmpty()){
            int len = que.size();
            int max = Integer.MIN_VALUE;
            for(int i = 0; i < len; i++){
                TreeNode poll = que.pollFirst();
                max = Math.max(max, poll.val);

                if(poll.left != null){
                    que.addLast(poll.left);
                }
                if(poll.right != null){
                    que.addLast(poll.right);
                }
            }
            list.add(max);
        }

        return list;
    }
}

力扣题目:116. 填充每个节点的下一个右侧节点指针

class Solution {
    public Node connect(Node root) {
        Deque<Node> que = new LinkedList<>();

        if(root == null){
            return root;
        }

        que.offerLast(root);
        while(!que.isEmpty()){
            int len = que.size();

            Node cur = que.poll();
            if (cur.left != null) que.add(cur.left);
            if (cur.right != null) que.add(cur.right);

            for(int i = 1; i < len; i++){
               Node next = que.poll();
               if (next.left != null) que.add(next.left);
               if (next.right != null) que.add(next.right);
               cur.next = next;
               cur = next;
            }
        }

        return root;
    }
}

力扣题目:填充每个节点的下一个右侧节点指针 II

本题只是换了一种树,但思路代码都是一样的

力扣题目:104. 二叉树的最大深度

class Solution {
    public int maxDepth(TreeNode root) {
        int deep = 0;
        Deque<TreeNode> que = new LinkedList<>();

        if(root == null){
            return deep;
        }

        que.offerLast(root);
        while(!que.isEmpty()){
            deep++;
            int len = que.size();

            for(int i = 0; i < len; i++){
                TreeNode node = que.poll();
                if(node.left != null){
                    que.offer(node.left);
                }
                if(node.right != null){
                    que.offer(node.right);
                }
            }
        }

        return deep;
    }
}

力扣题目:111. 二叉树的最小深度

class Solution {
    public int minDepth(TreeNode root) {
        int deep = 0;
        Deque<TreeNode> que = new LinkedList<>();

        if(root == null){
            return deep;
        }

        que.offerLast(root);
        while(!que.isEmpty()){
            deep++;
            int len = que.size();
            while(len > 0){
                TreeNode node = que.poll();
                if(node.left == null && node.right == null){
                    return deep;
                }
                if(node.left != null){
                    que.offer(node.left);
                }
                if(node.right != null){
                    que.offer(node.right);
                }

                len--;
            }
        }
        return deep;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/181747.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java:基于XML的Spring使用

基于XML的Spring使用一、Spring IOC 底层实现1.1 BeanFactory与ApplicationContexet1.2 图解IOC类的结构二、 Spring依赖注入数值问题【重点】2.1 字面量数值2.2 CDATA区2.3 外部已声明bean及级联属性赋值2.4 内部bean2.5 集合三、 Spring依赖注入方式【基于XML】3.1 set注入3.…

白炽灯护眼还是LED护眼?盘点专业护眼的LED护眼灯

目前大多数家庭都会购买台灯使用&#xff0c;选择白炽灯还是LED灯呢&#xff1f;建议是LED灯更护眼。白炽灯缺点&#xff1a;耗电、发光效率低、温度过高不安全。白炽灯优点&#xff1a;体积小、显色能力好。LED灯缺点:价格较高、显色能力比白炽灯弱一些。LED灯优点&#xff1a…

JDBC(powernode CD2206)详尽版(内含教学视频、源代码、SQL文件)

JDBC&#xff08;powernode CD2206&#xff09;详尽版&#xff08;内含教学视频、源代码、SQL文件&#xff09; 包含&#xff1a;教学视频、源代码&#xff08;与博客同步&#xff09;、SQL文件 下载链接地址&#xff1a; https://download.csdn.net/download/weixin_4641135…

使用kubebuilder开发operator详解--踩坑记录

跟着教程&#xff1a;使用kubebuilder开发operator详解出现&#xff1a; 国内无法访问该ip&#xff0c;需要设置go env&#xff1a; go envGOPROXYhttps://goproxy.c 查看go env&#xff1a; 修改镜像后仍然无法解决&#xff1a;借鉴该问题https://github.com/goproxy/goprox…

springboot-druid数据源的配置方式及配置后台监控-自定义和导入stater(推荐-简单方便使用)两种方式配置druid数据源

springboot-druid数据源的配置方式及配置后台监控-自定义和导入stater&#xff08;推荐-简单方便使用&#xff09;两种方式配置druid数据源druid数据源自定义配置druid数据源1.引入依赖2.配置自定义dataSoruce的Bean组件3.测试sql,验证数据源是否配置成功4.开启 StatFilter,wal…

哈希的应用 -- 布隆过滤器

作者&#xff1a;小萌新 专栏&#xff1a;C进阶 作者简介&#xff1a;大二学生 希望能和大家一起进步&#xff01; 本篇博客简介&#xff1a;介绍并模拟实现哈希的应用 – 布隆过滤器 布隆过滤器布隆过滤器的提出布隆过滤器的概念布隆过滤器的实现框架与算法插入函数查找函数删…

JVM学习(五):JVM运行时参数

一、JVM参数选项1.1 标准参数选项标准参数选项的特点是以-开头&#xff0c;比较稳定&#xff0c;后续版本基本不会变化也就是在命令行输入java 或 java -help之后显示的参数&#xff0c;其中选项包括:-d32 使用 32 位数据模型 (如果可用)-d64 使用 64 位数据模型 (如果可用)-…

Spring Security in Action 第十章 SpringSecurity应用CSRF保护和CORS跨域请求

本专栏将从基础开始&#xff0c;循序渐进&#xff0c;以实战为线索&#xff0c;逐步深入SpringSecurity相关知识相关知识&#xff0c;打造完整的SpringSecurity学习步骤&#xff0c;提升工程化编码能力和思维能力&#xff0c;写出高质量代码。希望大家都能够从中有所收获&#…

分布式链路追踪SkyWalking快速入门之环境安装界面指标介绍(一)

目录 一、先抛几个分布式常见的问题 二、分布式链路追踪Skywalking介绍 2.1 Skywalking是什么 2.2 市场上同类解决方案 2.3 skywalking的性能对比 三、Apache Skywalking特点和整体架构组件介绍 3.1 Skywalking特点 3.2 Skywalking整体架构 3.3 部署组件介绍 四.Apac…

HTML当中元素的id属性

<!DOCTYPE html> <html> <head> <meta charset"utf-8"> <title>HTML当中元素的id属性</title> </head> <body> <!-- 1、在HTML文档当中&#xff0c;任何元素/节…

详解promise与手写实现

详解promise与手写实现Promise1、Promise介绍与基本使用1.1 Promise概述1.2 Promise的作用1.3 Promise的使用2、Promise API3、Promise关键问题4、Promise自定义封装5、async与await5.1. mdn文档5.2.async函数5.3.await表达式5.4.注意Promise 1、Promise介绍与基本使用 1.1 P…

5.1 频率响应概述

一、研究放大电路频率响应的必要性 在放大电路中&#xff0c;由于电抗元件&#xff08;如电容、电感线圈等&#xff09;及半导体管极间电容的存在&#xff0c;当输入信号的频率过低或过高时&#xff0c;不但放大倍数的数值会变小&#xff0c;而且还将产生超前或者滞后的相移&a…

LightOJ 1197 - Help Hanzo (区间筛)

题目链接&#xff1a;Help Hanzo - LightOJ 1197 - Virtual Judge (vjudge.net) 题意 多组数据&#xff0c;每组输入两个数a&#xff0c;b&#xff0c;求区间a&#xff0c;b内的素数个数。 其中. 思路 首先我们看到数据范围就能知道&#xff0c;传统的质数筛肯定行不通了 …

苹果营收下降,但仍赚钱!

导读苹果公司今天发布2016财年第四财季财报&#xff0c;财报数据虽然略微超过分析师预期&#xff0c;但苹果公司的股价在盘后交易中曾上涨不过财报发布后很快下跌。 敲黑板概括苹果公司的财报的重点有&#xff1a;营收和盈利同比双双下滑、连续第三个季度下滑并出现2001年来首次…

高阶数据结构 位图的模拟实现

作者&#xff1a;学习同学 专栏&#xff1a;数据结构进阶 作者简介&#xff1a;大二学生 希望能和大家一起进步&#xff01; 本篇博客简介&#xff1a;模拟实现高阶数据结构位图 位图的模拟实现bitset类要实现的接口函数总览bitset类的模拟实现位图结构构造函数set reset flip …

全国地级市1999—2020年用地面积指标(建设用地\居住用地\绿地\建成区等)

在之前的文章中我们介绍过基于2000-2021年《中国城市统计年鉴》整理的人口相关指标&#xff0c;包括人口及户数数据和人口变动数据&#xff08;可查看之前推送的文章&#xff09;。 本次我们对2000—2021年的《中国城市统计年鉴》中的用地面积相关的指标进行了整理&#xff0c…

lego-loam学习笔记(二)

前言&#xff1a; 对于lego-loam中地面点提取部分的源码进行学习。 地面点提取在src/imageProjection.cpp中的函数groundRemoval()。内容比较少&#xff0c;容易理解。 size_t lowerInd, upperInd;float diffX, diffY, diffZ, angle; lowerInd表示低线数的点云&#xff1b; …

从网络摄像头拉流的几种方法(python代码)

文章目录摘要&#x1f407;1、直接使用OpenCV&#x1f407;2、使用ffmpeg&#x1f407;2.1、安装方法 &#x1f407;2.1.1、安装ffmpeg-python &#x1f407;2.1.2、安装FFmpeg &#x1f407;2.2、代码实现&#x1f407;3、多线程的方式读取图片&#x1f407;4、多进程的方式拉…

DocuWare 智能文档控制——杜绝成堆的文件和文件混乱,保证业务连续性,创建企业新阶段

一、智能文档控制——杜绝成堆的文件和文件混乱&#xff0c;保证业务连续性&#xff0c;创建企业新阶段 清晰有条理和即时可用的信息是成功的业务流程的关键&#xff0c;随时随地安全管理业务文档&#xff0c;快速查找并智能使用它们。 1、安全存储 使用安全的集中式平台存放…

44.Isaac教程--姿态估计

二维骨骼姿态估计 ISAAC教程合集地址: https://blog.csdn.net/kunhe0512/category_12163211.html 文章目录二维骨骼姿态估计应用概述推理运行推理在嵌入式平台上运行推理消息类型小码推理示例训练步骤 1. 先决条件 安装 Docker 容器步骤 2. 安装步骤 3. 下载 COCO 2017 和预处理…