二叉树的层次遍历(用队列来实现)

#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50

typedef char ElemType;

typedef struct BTNode
{
	ElemType data;
	struct BTNode *left;
	struct BTNode *right;
}BTNode,*BiTree;

typedef struct Queue
{
	BTNode *data[MaxSize]; //注意这里的data要设置为树节点类型
	int rear,front;
}Queue;

void InitQueue(Queue &Q) //初始化栈
{
	Q.rear = Q.front = 0;
}

bool IsQueueEmpty(Queue Q) //判断栈是否为空
{
	if(Q.front == Q.rear)
		return true;
	else
		return false;
}

void EnQueue(Queue &Q,BTNode *B) //进队列
{
	Q.data[Q.rear] = B;
	Q.rear = (Q.rear+1)%MaxSize;
}

void DeQueue(Queue &Q,BTNode *&B) //出队列
{
	B = Q.data[Q.front];
	Q.front = (Q.front+1)%MaxSize;
}

void createBiTree(BTNode *&BT) //创建二叉树
{
	ElemType ch;
	scanf("%c",&ch);
	if(ch==' ')
		BT=NULL;
	else
	{
		BT = (BTNode*)malloc(sizeof(BTNode));
		BT->data = ch;
		createBiTree(BT->left);
		createBiTree(BT->right);
	}
}

void DLR(BiTree B) //先序遍历二叉树
{
	if(B)
	{
		printf("%c ",B->data);
		DLR(B->left);
		DLR(B->right);
	}
}

void levelOrder(BiTree B) //层次遍历二叉树
{
	Queue Q;
	BTNode *x;
	InitQueue(Q);
	if(B)
		EnQueue(Q,B);
	else
		printf("空树!\n");
	while(!IsQueueEmpty(Q))
	{
		DeQueue(Q,x);
		if(x)
		{
			printf("%c ",x->data);
			EnQueue(Q,x->left);
			EnQueue(Q,x	->right);
		}
	}
	printf("\n");
}


void main()
{
	BiTree B;
	createBiTree(B);
	printf("先序遍历:");
	DLR(B);
	printf("\n");
	printf("层次遍历:");
	levelOrder(B);
}



按先序遍历来依次输入二叉树结点,若无孩子结点则输入空格。

如输入:

ABD  E  CF   

输出:

先序遍历:A B D E C F

层次遍历:A B C D E F

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值