二叉树的层次遍历

二叉树的层次遍历

利用队列依次存储要访问的节点

void LevelOrderTraverse(BiTree T)
{
	LinkQueue Q; //定义队列
	InitQueue(&Q); //初始化队列
	BiTNode BT;
	if(T)
	{
		InsertQueue(&Q, *T); //根节点指针入队列
	}
	while(EmptyQueue(Q)) //队列不空时
	{
		DeleteQueue(&Q, &BT); //出队列
		visit(BT.data);//输出该节点的值
		if(BT.lchild != NULL)
		{
			InsertQueue(&Q, *BT.lchild); //有左孩子就把左孩子入队列
		}
		if(BT.rchild != NULL)
		{
			InsertQueue(&Q, *BT.rchild); //有右孩子就把右孩子入队列
		}
	}
}

整体代码如下

#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
	ElemType data;
	struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
typedef struct QNode
{
	BiTNode  node;
	struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
	QueuePtr front;
	QueuePtr rear;
} LinkQueue;

void InitQueue(LinkQueue *Q);
void InsertQueue(LinkQueue *q, BiTNode e);
void DeleteQueue(LinkQueue *q, BiTNode *e);
int EmptyQueue(LinkQueue Q);
void visit(char c);
void LevelOrderTraverse(BiTree T);

int main()
{
	BiTree T;
	CreateBiTree(&T);
	LevelOrderTraverse(T);
}
void InitQueue(LinkQueue *Q)//初始化一个空队列
{
	Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
	if(!Q->front)
	{
		exit(0);
	}
	else
	{
		Q->front->next = NULL;
	}
}

void InsertQueue(LinkQueue *q, BiTNode e)//入队列操作
{
	QueuePtr p;
	p = (QueuePtr)malloc(sizeof(QNode));
	if(p == NULL)
	{
		exit(0);
	}
	p->node = e;
	p->next = NULL;
	q->rear ->next = p;
	q->rear = p;
}

void DeleteQueue(LinkQueue *q, BiTNode *e)//出队列操作
{
	QueuePtr p;
	if(q->front == q->rear)
	{
		return ;
	}
	p = q->front->next;
	*e = p->node;
	q->front->next = p->next;
	if(q->rear == p)
	{
		q->rear = q->front;
	}
	free(p);
}
int EmptyQueue(LinkQueue Q)
{
	return (Q.front == Q.rear ? 0 :  1);
}
void visit(char c)
{
	printf("%c", c); 
}

void LevelOrderTraverse(BiTree T)
{
	LinkQueue Q; //定义队列
	InitQueue(&Q); //初始化队列
	BiTNode BT;
	if(T)
	{
		InsertQueue(&Q, *T); //根节点指针入队列
	}
	while(EmptyQueue(Q)) //队列不空时
	{
		DeleteQueue(&Q, &BT); //出队列
		visit(BT.data);//输出该节点的值
		if(BT.lchild != NULL)
		{
			InsertQueue(&Q, *BT.lchild); //有左孩子就把左孩子入队列
		}
		if(BT.rchild != NULL)
		{
			InsertQueue(&Q, *BT.rchild); //有右孩子就把右孩子入队列
		}
	}
}
void CreateBiTree(BiTree *T)
{
	char c;
	scanf("%c", &c);
	if(' ' == c)
	{
		*T = NULL;
	}
	else
	{
		*T = (BiTNode *)malloc(sizeof(BiTNode));
		(*T)->data = c;
		CreateBiTree(&(*T)->lchild);
		CreateBiTree(&(*T)->rchild);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值