二叉树层次遍历思路就是使用队列进行存储,当出队一个元素,则将其左右子树入队。

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>


#define MaxSize 10



typedef struct Tree {

	int data;					//	存放数据域
	struct Tree* lchild;			//	遍历左子树指针
	struct Tree* rchild;			//	遍历右子树指针

}Tree, * BitTree;
//队的数据结构
typedef struct sqqueue
{
	BitTree data[MaxSize];
	int front,
		rear;
}sqqueue;

//初始化
void Initqueue(sqqueue* s)
{
	s->front = s->rear = 0;
}
//判断是否为空
int queueEmpty(sqqueue s)
{
	return s.front == s.rear;
}
//入队
void EnQueue(sqqueue* s, int x)
{
	if ((s->rear + 1) % MaxSize == s->front)
	{
		printf("队满");
		return;
	}
	s->data[s->rear] = x;
	s->rear = (s->rear + 1) % MaxSize;
}
//出队
void OutQueue(sqqueue* s)
{
	s->front = (s->front + 1) % MaxSize;
}






BitTree CreateLink()
{
	int data;
	int temp;
	BitTree T;

	scanf("%d", &data);		//	输入数据
	temp = getchar();			//	吸收空格

	if (data == -1) {			//	输入-1 代表此节点下子树不存数据,也就是不继续递归创建

		return NULL;

	}
	else {
		T = (BitTree)malloc(sizeof(Tree));			//		分配内存空间
		T->data = data;								//		把当前输入的数据存入当前节点指针的数据域中

		printf("请输入%d的左子树: ", data);
		T->lchild = CreateLink();					//		开始递归创建左子树
		printf("请输入%d的右子树: ", data);
		T->rchild = CreateLink();					//		开始到上一级节点的右边递归创建左右子树
		return T;							//		返回根节点
	}

}
void levelOrder(BitTree T)
{
	sqqueue s;
	Initqueue(&s);
	EnQueue(&s,T);
	BitTree P;
	while (!queueEmpty(s))
	{
		printf("%d\t",s.data[s.front]->data);
		P = s.data[s.front];
		OutQueue(&s);
		if(P->lchild!=NULL)
			EnQueue(&s, P->lchild);
		if(P->rchild!=NULL)
			EnQueue(&s, P->rchild);
	}
}


int main()
{
	BitTree S;
	printf("请输入第一个节点的数据:\n");
	S = CreateLink();			//		接受创建二叉树完成的根节点
	printf("\n层次遍历结果: \n");
	levelOrder(S);
	return 0;
}

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐