当前位置: 首页 > news >正文

【算法系列-二叉树】层序遍历

【算法系列-二叉树】层序遍历

文章目录

  • 【算法系列-二叉树】层序遍历
    • 1. 算法分析🛸
    • 2. 相似题型🎯
      • 2.1 二叉树的层序遍历II(LeetCode 107)
      • 2.2 二叉树的右视图(LeetCode 199)
      • 2.3 二叉树的层平均值(LeetCode 637)
      • 2.4 N叉树的层序遍历(LeetCode 429)
      • 2.5 在每个树行中找最大值(LeetCode 515)
      • 2.6 填充每个节点的下一个右侧节点指针(LeetCode 116)
      • 2.7 二叉树的最大深度(LeetCode 104)
      • 2.8 二叉树的最小深度(LeetCode 111)

1. 算法分析🛸

二叉树的层序遍历就是对树进行广度优先搜索,一层一层的对树的节点进行遍历;

【题目链接】102. 二叉树的层序遍历 - 力扣(LeetCode)

在这里,我们通过队列来辅助实现二叉树的层序遍历,关键在于寻找到判断当前节点正在哪一层这一层的节点是否遍历完的条件。

解题过程🎬

定义一个size,这个size等于当前队列的长度大小

开始先将根节点加入队列,形成第一层; 此时size = 1,再将队列中的节点弹出,将该节点的左右节点加入队列(非空),同时size - 1;

重复上述过程,直到size = 0时,表示当前层数的节点已经遍历完,进入下一层,直到队列为空,返回结果

代码示例🌰

class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> ret = new ArrayList<>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {List<Integer> list = new ArrayList<>();int size = queue.size();while (size > 0) {TreeNode cur = queue.poll();list.add(cur.val);if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}ret.add(list);}return ret;}
}

下面提供一些与层序遍历解法相似的类型题:

2. 相似题型🎯

2.1 二叉树的层序遍历II(LeetCode 107)

【题目链接】107. 二叉树的层序遍历 II - 力扣(LeetCode)

代码示例🌰

class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> ret = new ArrayList<>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {List<Integer> list = new ArrayList<>();int size = queue.size();while (size > 0) {TreeNode cur = queue.poll();list.add(cur.val);if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}ret.add(0, list);}return ret;}
}

2.2 二叉树的右视图(LeetCode 199)

【题目链接】199. 二叉树的右视图 - 力扣(LeetCode)

解题思路与使用队列的层序遍历相同,需要注意的是要找到能够在右视图看到的节点,这个节点可以是左节点也可以是右节点,但它一定是每一层遍历的最右边节点,对此在遍历到队列中size为0的前一个节点时,将这个节点的值加入返回数组即可

代码示例🌰

class Solution {public List<Integer> rightSideView(TreeNode root) {List<Integer> ret = new ArrayList<>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();while (size > 1) {queueOfferNode(queue);size--;}TreeNode node = queueOfferNode(queue);ret.add(node.val);}return ret;}TreeNode queueOfferNode(Queue<TreeNode> queue) {TreeNode cur = queue.poll();if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}return cur;}
}

2.3 二叉树的层平均值(LeetCode 637)

【题目链接】637. 二叉树的层平均值 - 力扣(LeetCode)

代码示例🌰

class Solution {public List<Double> averageOfLevels(TreeNode root) {List<Double> ret = new ArrayList<>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();int num = size;double sum = 0;while (size > 0) {TreeNode cur = queue.poll();sum += cur.val;if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}ret.add(sum / num);}return ret;}
}

2.4 N叉树的层序遍历(LeetCode 429)

【题目链接】429. N 叉树的层序遍历 - 力扣(LeetCode)

代码示例🌰

/*
// Definition for a Node.
class Node {public int val;public List<Node> children;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, List<Node> _children) {val = _val;children = _children;}
};
*/class Solution {public List<List<Integer>> levelOrder(Node root) {List<List<Integer>> ret = new ArrayList<>();if (root == null) {return ret;}Queue<Node> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {List<Integer> list = new ArrayList<>();int size = queue.size();while (size > 0) {Node cur = queue.poll();list.add(cur.val);List<Node> children = cur.children;for (Node node : children) {if (node != null) {queue.offer(node);}}size--;}ret.add(list);}return ret;}
}

2.5 在每个树行中找最大值(LeetCode 515)

【题目链接】515. 在每个树行中找最大值 - 力扣(LeetCode)

代码示例🌰

class Solution {public List<Integer> largestValues(TreeNode root) {List<Integer> ret = new ArrayList<>();if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();int max = Integer.MIN_VALUE;while (size > 0) {TreeNode cur = queue.poll();if (cur.val > max) {max = cur.val;}if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}ret.add(max);}return ret;}
}

2.6 填充每个节点的下一个右侧节点指针(LeetCode 116)

【题目链接】116. 填充每个节点的下一个右侧节点指针 - 力扣(LeetCode)

代码示例🌰

/*
// Definition for a Node.
class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, Node _left, Node _right, Node _next) {val = _val;left = _left;right = _right;next = _next;}
};
*/class Solution {public Node connect(Node root) {if (root == null) {return root;}Queue<Node> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {int size = queue.size();while (size-- > 0) {Node cur1 = queue.poll();Node cur2 = size == 0 ? null : queue.peek();cur1.next = cur2;if (cur1.left != null) {queue.offer(cur1.left);}if (cur1.right != null) {queue.offer(cur1.right);}}}return root;}
}

2.7 二叉树的最大深度(LeetCode 104)

【题目链接】104. 二叉树的最大深度 - 力扣(LeetCode)

代码示例🌰

class Solution {public int maxDepth(TreeNode root) {int ret = 0;if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {ret++;int size = queue.size();while (size > 0) {TreeNode cur = queue.poll();if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}}return ret;}
}

2.8 二叉树的最小深度(LeetCode 111)

【题目链接】111. 二叉树的最小深度 - 力扣(LeetCode)

代码示例🌰

class Solution {public int minDepth(TreeNode root) {int ret = 0;if (root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {ret++;int size = queue.size();while (size > 0) {TreeNode cur = queue.poll();if (cur.left == null && cur.right == null) {return ret;}if (cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}size--;}}return ret;}
}

以上便是对二叉树层序遍历问题的介绍了!!后续还会继续分享其它算法系列内容,如果这些内容对大家有帮助的话请给一个三连关注吧💕( •̀ ω •́ )✧( •̀ ω •́ )✧✨

相关文章:

【算法系列-二叉树】层序遍历

【算法系列-二叉树】层序遍历 文章目录 【算法系列-二叉树】层序遍历1. 算法分析&#x1f6f8;2. 相似题型&#x1f3af;2.1 二叉树的层序遍历II(LeetCode 107)2.2 二叉树的右视图(LeetCode 199)2.3 二叉树的层平均值(LeetCode 637)2.4 N叉树的层序遍历(LeetCode 429)2.5 在每个…...

我的世界方块改进版

引子 之前文章的磁性方块&#xff0c;通过3D打印实现&#xff0c;也批量打印了一些&#xff0c;下图就是一个小树 使用过程中&#xff0c;发现磁力感觉不紧&#xff0c;所以想改进一版。 正文 之前的结构如下&#xff1a;&#xff1a; 如果出现相邻的空隙间的磁铁相互作用&am…...

博客搭建之路:hexo增加搜索功能

文章目录 hexo增加搜索功能本地搜索弊端algolia搜索 hexo增加搜索功能 hexo版本5.0.2 npm版本6.14.7 next版本7.8.0 作为一个博客&#xff0c;没有搜索功能&#xff0c;如何在大批文章中找到自己想要的&#xff0c;那在hexo中如何增加搜索功能呢&#xff1f; search:path: sea…...

2024年最新互联网大厂精选 Java 面试真题集锦(JVM、多线程、MQ、MyBatis、MySQL、Redis、微服务、分布式、ES、设计模式)

前言 春招&#xff0c;秋招&#xff0c;社招&#xff0c;我们 Java 程序员的面试之路&#xff0c;是挺难的&#xff0c;过了 HR&#xff0c;还得被技术面&#xff0c;在去各个厂面试的时候&#xff0c;经常是通宵睡不着觉&#xff0c;头发都脱了一大把&#xff0c;还好最终侥幸…...

MybatisPlus入门(一)MybatisPlus简介

一、MyBatis简介 MyBatisPlus&#xff08;简称MP&#xff09;是基于MyBatis框架基础上开发的增强型工具&#xff0c;旨在简化开发、提高效率 - 官网&#xff1a;https://mybatis.plus/ https://mp.baomidou.com/ MyBatisPlus特性&#xff1a; - 无侵入&#xff1a;只做增强…...

QoS学习笔记

QoS业务分类 基于 DiffServ 服务模型的 QoS 业务可以分为以下几大类&#xff1a; 流分类和标记&#xff08;Traffic classification and marking&#xff09;&#xff1a;要实现差分服务&#xff0c;需要首先将数据包分为不同的类别或者设置为不同的优先级。将数据包分为不同…...

图(邻接矩阵)知识大杂烩!!(邻接矩阵结构,深搜,广搜,prim算法,kruskal算法,Dijkstra算法,拓扑排序)(学会一文让你彻底搞懂!!)

小伙伴们大家好&#xff0c;今天给大家带来图&#xff08;邻接矩阵&#xff09;的各种知识&#xff0c;让你看完此文章彻底学会邻接矩阵的相关问题。 1.邻接矩阵表示方法 1.1知识讲解 我们用一个二维数组arr来表示图。若图为有向图&#xff0c;其中arr【i】【j】w表示i号点和…...

Prometheus自定义PostgreSQL监控指标

本文我们将介绍如何在Prometheus中创建自定义PostgreSQL指标。默认情况下由postgres_export运行的查询可能不能满足用户需求&#xff0c;但我们可以创建自定义查询&#xff0c;并要求postgres_exporter公开自定义查询的结果。postgres_exporter最近被移到了Prometheus Communit…...

400行程序写一个实时操作系统(十六):操作系统中的调度策略

前言 在前面我们完成了Sparrow的临界区的代码&#xff0c;使用临界区&#xff0c;能够解决常见的并发问题&#xff0c;现在该完善我们的调度算法了。 调度算法在操作系统领域常常是热门的话题。不同的用途将会使用不同的调度策略。在本节&#xff0c;笔者将为大家介绍一些操作…...

从安灯系统看汽车零部件工厂的智能制造转型

在当今快速发展的制造业领域&#xff0c;汽车零部件工厂正面临着日益激烈的市场竞争和不断提高的客户需求。为了在竞争中脱颖而出&#xff0c;实现可持续发展&#xff0c;许多汽车零部件工厂纷纷踏上智能制造转型之路。而安灯系统作为一种重要的生产管理工具&#xff0c;在这场…...

SwiftUI(三)- 渐变、实心形状和视图背景

引言 在现代的应用的UI设计中&#xff0c;渐变和形状背景为界面带来了丰富的层次与视觉效果&#xff0c;而SwiftUI提供了一系列简单且强大的API&#xff0c;可以轻松实现这些效果。在这篇文章中&#xff0c;我们将介绍SwiftUI中的渐变、实心形状和视图背景的基础用法&#xff…...

RK3568-ota升级

ota升级 OTA&#xff08;Over-the-Air&#xff09;即空间下载技术。 OTA 升级是 Android 系统提供的标准软件升级方式。它功能强大&#xff0c;可以无损失升级系统&#xff0c;主要通过网络&#xff0c;例如 WIFI、3G/4G 自动下载 OTA 升级包、自动升级&#xff0c;也支持通过…...

GR-ConvNet代码详解

GR-ConvNet代码详解 文章目录 GR-ConvNet代码详解前言一、utils1.dataset_processing1.image.py1.Iamge类2.DepthImage类3.WidthImage类 2.grasp.py1. _gr_text_to_no()方法2.GraspRectangles类3.GraspRectangle类3.Grasp类4.detect_grasps方法 3.generate_cornell_depth.py4.e…...

Excel自带傅里叶分析数据处理——归一化处理

在Excel工具中&#xff0c;默认情况下数据处理---傅里叶分析通常不进行归一化处理&#xff0c;需要用户手动进行归一化处理。 &#xff08;1&#xff09;傅里叶变换的原理 傅里叶变换将时域信号转换为频域信号&#xff0c;输出的是复数形式的频率分量&#xff0c;包含了幅值和…...

Centos7.6版本安装mysql详细步骤

操作步骤&#xff1a; 1.下载Linux版本Mysql并上传至linux系统中 2.解压mysql并查询系统中是否有相关软件存在以及配置mysql,启动mysql tar -zxvf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz tar -zxvf mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz rpm -qa|grep mysql ##查…...

寄宿学校:为自闭症儿童提供全面的教育和关爱

在这个多彩的世界里&#xff0c;每一个生命都值得被温柔以待&#xff0c;每一颗心灵都值得被悉心呵护。然而&#xff0c;自闭症儿童这一特殊群体&#xff0c;他们的世界却常常被误解和忽视。幸运的是&#xff0c;有一种教育模式——寄宿学校&#xff0c;正为这些孩子打开了一扇…...

LLaMA Factory环境配置

LLaMA-Factory官方文档 安装正确的torch和cuda版本 参考&#xff1a; PyTorch 报错解决 1.ImportError: /usr/lib/x86_64-linux-gnu/libstdc.so.6: version GLIBCXX_3.4.29 not found 参考这个解决&#xff1a;丝滑解决ImportError: /usr/lib/x86_64-linux-gnu/libstdc.s…...

STM32实现毫秒级时间同步

提起“时间同步”这个概念&#xff0c;大家可能很陌生。一时间搞不清楚是什么意思。 我理解“时间同步”可以解决多个传感器采集数据不同时的问题&#xff0c;让多个传感器同时采集数据。 打个比方。两个人走路&#xff0c;都是100毫秒走一步&#xff08;频率相同是前提&…...

瑞吉外卖之com.fasterxml.jackson.dataformat.cbor.CBORFactor相关报错

1.报错&#xff1a;Error creating bean with name routerFunctionMapping defined in class path resource [com/itheima/reggie/config/WebMvcConfig.class]: Failed to instantiate [org.springframework.web.servlet.function.support.RouterFunctionMapping]: Factory met…...

CSS - grid制作表格

1. grid-template-columns&#xff1a;网格布局中的列的数量&#xff0c;也可以设置列的宽度 .grid-container {display: grid;grid-template-columns: 80px 200px auto 40px; }.grid-container {display: grid;grid-template-columns: auto auto auto auto;//表示所有列的宽度…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

uniapp微信小程序视频实时流+pc端预览方案

方案类型技术实现是否免费优点缺点适用场景延迟范围开发复杂度​WebSocket图片帧​定时拍照Base64传输✅ 完全免费无需服务器 纯前端实现高延迟高流量 帧率极低个人demo测试 超低频监控500ms-2s⭐⭐​RTMP推流​TRTC/即构SDK推流❌ 付费方案 &#xff08;部分有免费额度&#x…...

Caliper 配置文件解析:config.yaml

Caliper 是一个区块链性能基准测试工具,用于评估不同区块链平台的性能。下面我将详细解释你提供的 fisco-bcos.json 文件结构,并说明它与 config.yaml 文件的关系。 fisco-bcos.json 文件解析 这个文件是针对 FISCO-BCOS 区块链网络的 Caliper 配置文件,主要包含以下几个部…...

LLMs 系列实操科普(1)

写在前面&#xff1a; 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容&#xff0c;原视频时长 ~130 分钟&#xff0c;以实操演示主流的一些 LLMs 的使用&#xff0c;由于涉及到实操&#xff0c;实际上并不适合以文字整理&#xff0c;但还是决定尽量整理一份笔…...

如何应对敏捷转型中的团队阻力

应对敏捷转型中的团队阻力需要明确沟通敏捷转型目的、提升团队参与感、提供充分的培训与支持、逐步推进敏捷实践、建立清晰的奖励和反馈机制。其中&#xff0c;明确沟通敏捷转型目的尤为关键&#xff0c;团队成员只有清晰理解转型背后的原因和利益&#xff0c;才能降低对变化的…...

Qt 事件处理中 return 的深入解析

Qt 事件处理中 return 的深入解析 在 Qt 事件处理中&#xff0c;return 语句的使用是另一个关键概念&#xff0c;它与 event->accept()/event->ignore() 密切相关但作用不同。让我们详细分析一下它们之间的关系和工作原理。 核心区别&#xff1a;不同层级的事件处理 方…...

CVPR2025重磅突破:AnomalyAny框架实现单样本生成逼真异常数据,破解视觉检测瓶颈!

本文介绍了一种名为AnomalyAny的创新框架&#xff0c;该方法利用Stable Diffusion的强大生成能力&#xff0c;仅需单个正常样本和文本描述&#xff0c;即可生成逼真且多样化的异常样本&#xff0c;有效解决了视觉异常检测中异常样本稀缺的难题&#xff0c;为工业质检、医疗影像…...

c# 局部函数 定义、功能与示例

C# 局部函数&#xff1a;定义、功能与示例 1. 定义与功能 局部函数&#xff08;Local Function&#xff09;是嵌套在另一个方法内部的私有方法&#xff0c;仅在包含它的方法内可见。 • 作用&#xff1a;封装仅用于当前方法的逻辑&#xff0c;避免污染类作用域&#xff0c;提升…...

自然语言处理——文本分类

文本分类 传统机器学习方法文本表示向量空间模型 特征选择文档频率互信息信息增益&#xff08;IG&#xff09; 分类器设计贝叶斯理论&#xff1a;线性判别函数 文本分类性能评估P-R曲线ROC曲线 将文本文档或句子分类为预定义的类或类别&#xff0c; 有单标签多类别文本分类和多…...

快速排序算法改进:随机快排-荷兰国旗划分详解

随机快速排序-荷兰国旗划分算法详解 一、基础知识回顾1.1 快速排序简介1.2 荷兰国旗问题 二、随机快排 - 荷兰国旗划分原理2.1 随机化枢轴选择2.2 荷兰国旗划分过程2.3 结合随机快排与荷兰国旗划分 三、代码实现3.1 Python实现3.2 Java实现3.3 C实现 四、性能分析4.1 时间复杂度…...