当前位置:网站首页>二叉树的层序遍历(C语言实现)
二叉树的层序遍历(C语言实现)
2022-07-26 13:44:00 【ndream的三水】
层序遍历代码思路
借助一个辅助队列。
- 先将二叉树的根结点入队,
- 然后出队,访问出队结点,
- 若它有左子树,则将左子树根节点入队;
- 若它有右子树,则将右子树根节点入队。
- 然后出队,
- 访问出队结点……如此反复,直到队列为空
void LevelOrder(BiTree T)
{
InitQueue(&Q); // 初始化辅助队列
BiTree p;
EnQueue(&Q, T); // 将根节点入队
while(!IsEmpty(Q)) // 队列不空则循环
{
DeQueue(Q, p); // 队头结点出队
visit(p);
if (p->lchild != NULL)
{
EnQueue(Q, p->lchild); // 左子树不空,则左子树根节点入队
}
if (p->rchild != NULL)
{
EnQueue(Q, p->rchild); // 右子树不空,则右子树根节点入队
}
}
}
实现过程
根据上面的代码思路,需要实现两个数据结构,一个二叉树,一个队列,需要实现的功能有
- 二叉树、队列的数据结构定义
- 二叉树的创建、队列的初始化
- 二叉树的层序遍历、队列的出队、入队操作
代码实现

#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef char TElemType;
const int MAXSIZES = 50;
// 二叉树的存储结构
typedef struct BiTNode {
TElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
typedef BiTree QElemType;
// 队列的存储结构
typedef struct {
QElemType data[MAXSIZES];
int front;
int rear;
}SqQueue;
// 通过前序遍历创建二叉树
void CreateBiTree(BiTree *T)
{
TElemType ch;
scanf("%c", &ch);
if (ch == '#')
{
*T = NULL;
}
else
{
*T = (BiTree) malloc(sizeof(BiTNode));
if (!T)
{
exit(0);
}
(*T)->data = ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
// 初始化队列
void InitQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
}
// 辅助队列的入队操作
void EnQueue(SqQueue *Q, QElemType q)
{
if ((Q->rear + 1) % MAXSIZES == Q->front)
return;
Q->data[Q->rear] = q;
Q->rear = (Q->rear + 1) % MAXSIZES;
}
// 辅助队列的出队操作
void DeQueue(SqQueue *Q, QElemType *q)
{
if (Q->front == Q->rear)
return;
*q = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZES;
}
// 二叉树的中序遍历
void InOrderTraverse(BiTree T)
{
if (!T)
{
return;
}
InOrderTraverse(T->lchild);
printf("%c", T->data);
InOrderTraverse(T->rchild);
}
// 二叉树的层序遍历
void LevelOrder(BiTree T)
{
SqQueue Q;
InitQueue(&Q); // 初始化辅助队列
BiTree p;
EnQueue(&Q, T); // 将根节点入队
while(Q.front != Q.rear) // 队列不空则循环
{
DeQueue(&Q, &p); // 队头结点出队
printf("%c", p->data);
if (p->lchild != NULL)
{
EnQueue(&Q, p->lchild); // 左子树不空,则左子树根节点入队
}
if (p->rchild != NULL)
{
EnQueue(&Q, p->rchild); // 右子树不空,则右子树根节点入队
}
}
}
int main()
{
BiTree t;
printf("请按照前序扩展二叉树进行输入:(#表示空结点)\n");
CreateBiTree(&t);
printf("中序遍历: ");
InOrderTraverse(t);
printf("\n层序遍历: ");
LevelOrder(t);
return 0;
}
参考:
层序遍历思路来《王道数据结构》
边栏推荐
- 异步线程池在开发中的使用
- Parent class reference to child class (parent class reference points to child class object)
- Time complexity and space complexity
- 【开源之美】nanomsg(2) :req/rep 模式
- Force deduction ----- the number of words in the string
- Tupu 3D visual national style design | collision between technology and culture "cool" spark“
- 一文学透MySQL表的创建和约束
- 【黑马早报】字节旗下多款APP下架;三只松鼠脱氧剂泄露致孕妇误食;CBA公司向B站索赔4.06亿;马斯克否认与谷歌创始人妻子有婚外情...
- LCL three-phase PWM rectifier (inverter)
- Huawei computer test ~ offset realizes string encryption
猜你喜欢

天津市应急局与驻津央企签署协议深化应急联动机制建设

周伟:寻找非共识性投资机会,陪伴延迟满足的创始团队

.net6与英雄联盟邂逅之——根据官方LCU API制作游戏助手

Unity中序列化类为json格式

Win11+VS2019配置YOLOX

Zhou Wei: look for non consensual investment opportunities to accompany the founding team that delays satisfaction

We were tossed all night by a Kong performance bug

In 2022, we "sent away" so many Internet products in only one month

.net6 encounter with the League of heroes - create a game assistant according to the official LCU API

The shell script in Jenkins fails to execute but does not exit by itself
随机推荐
Precautions for triggering pytest.main() from other files
Photoshop (cc2020) unfinished
Detailed relation extraction model casrel
The picture moves horizontally with the phone - gyroscope. 360 degree setting conditions
421. 数组中两个数的最大异或值
万字长文,浅谈企业数字化建模蓝图
【OAuth2】八、OAuth2登录的配置逻辑-OAuth2LoginConfigurer和OAuth2ClientConfigurer
Algorithm -- continuous sequence (kotlin)
flutter多渠道打包运行
Research status and pain points of deep learning 3D human posture estimation at home and abroad
JSON data returned by controller
JUC summary
The shell script in Jenkins fails to execute but does not exit by itself
Abstract factory and its improvement examples
【着色器实现Overlay重新覆盖变装效果_Shader效果第九篇】
El table implements editable table
The serialization class in unity is in JSON format
Exploration on cache design optimization of community like business
向路由组件传递参数
TDSQL-C Serverless:助力初创企业实现降本增效