二叉树层序遍历

试写出层次遍历的算法
    分析:
        正如名字所表现的那样,要一层一层的遍历,这里我们就需要用到队列这种数据结构了,具体做法是:
        先将根节点入队,然后根节点出队,并依次将根节点的左孩子、右孩子入队。后续如此循环,直至队空

代码如下:

struct biTree {
	char data;
	struct biTree *lchild;
	struct biTree *rchild;
};
struct Squeue {
	biTree *arr;
	int front, rear;
};
#include <stdio.h>
#include <stdlib.h>
void levelOrder(biTree *T,Squeue *sq,int maxSize) {
	struct biTree *p = T;
	struct biTree *r = (struct biTree *)malloc(sizeof(struct biTree));
	bool enQueueS(Squeue *, biTree *, int);
	bool isEmpty(Squeue *);
	bool deQueueS(Squeue *, biTree *,int);
	enQueueS(sq,p,maxSize);
	while (!isEmpty(sq)) {
		deQueueS(sq,r,maxSize);
		printf("%c ",r->data);
		if(r->lchild)enQueueS(sq, r->lchild, maxSize);
		if (r->rchild)enQueueS(sq, r->rchild, maxSize);
	}
}
int main() {
	int count = 0;
	struct biTree *T = (struct biTree *)malloc(sizeof(struct biTree));
	struct Squeue *sq = (struct Squeue *)malloc(sizeof(struct Squeue));

	biTree *create(biTree *);
	void nodeNum(biTree *,int *);

	Squeue *createQueue(int);
	T = create(T);//创建一颗二叉树
	nodeNum(T,&count);//统计二叉树节点个数
	sq = createQueue(count);

	levelOrder(T,sq,count);
	return 0;
}

失败不可怕,可怕的是还没开始你就临阵逃脱。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北街学长

你的鼓励使我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值