C语言按层次力变二叉树算法,按层次顺序(同一层自左至右)遍历二叉树的算法

本文介绍了一种按层次顺序遍历二叉树的算法,该算法使用队列存储每一层的节点,并按顺序访问这些节点。文章提供了具体的代码实现,包括初始化队列、入队、出队等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写按层次顺序(同一层自左至右)遍历二叉树的算法。

二叉链表类型定义:

typedef char TElemType; // 设二叉树的元素为char类型

typedef struct BiTNode {

TElemType data;

BiTNode *lchild, *rchild;

} BiTNode, *BiTree;可用队列类型Queue的相关定义:

typedef BiTree QElemType; // 设队列元素为二叉树的指针类型

Status InitQueue(Queue &Q);

Status EnQueue(Queue &Q, QElemType e);

Status DeQueue(Queue &Q, QElemType &e);

Status GetHead(Queue Q, QElemType &e);

Status QueueEmpty(Queue Q);提示:可将遍历元素的值(字符)依次置入ss,并最后以'\0'结尾。

也可以用下列字符串函数产生ss:

int sprintf(char *buffer, char *format [, argument, ...]);

char *strcat(char *dest, char *src);实现函数如下:

void LevelOrder(BiTree bt, char *ss)

/* travel BiTree bt by level, Return result by ss. */

{

int i;

BiTree p;

Queue Q;

InitQueue(Q);

if(bt){

EnQueue(Q,bt);

while(!QueueEmpty(Q)){

DeQueue(Q,p);

ss[i++] = p -> data;//将二叉树中的元素依次存进ss

if(p -> lchild){

EnQueue(Q,p -> lchild);

}

if(p -> rchild){

EnQueue(Q,p -> rchild);

}

}

ss[i] = '\0';

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值