数据结构学习笔记-二叉树的层序遍历

二叉树层序遍历

        思想很简单利用队列的操作,首先根结点入队,然后从队首出队元素并输出,随后将该结点的左右孩子分别入队,重复上述过程,直到左右孩子均为NULL

程序中用到的结构体和队列操作:

typedef struct Btnode
{
	char data;
	struct Btnode *lchild;
	struct Btnode *rchild;
}BTNODE;

typedef struct Qnode
{
	BTNODE *value;
	struct Qnode *pNext;
}QNODE;

typedef struct Queue
{
	QNODE *front;
	QNODE *rear;
	int qlength;
}QUEUE;



void En_Queue(QUEUE *,BTNODE *);
void Init_Queue(QUEUE *);
BTNODE *De_Queue(QUEUE *);
int QueueEmpty(QUEUE *);

void level_traverse(BTNODE *);
BTNODE *Creat_Binary_Tree(BTNODE *);



void En_Queue(QUEUE *q,BTNODE *p)
{
	QNODE *pNew;
	pNew = (QNODE *)malloc(sizeof(QNODE));
	if(NULL==pNew)
	{
		printf("memory distribution error\n");
		exit(-1);
	}
	pNew->value = p;
	pNew->pNext = NULL;
	if(q->qlength==0)
	{
		q->rear = pNew;
		q->front = q->rear;
	}
	else
	{
		q->rear->pNext = pNew;
		q->rear = pNew;
	}
	++(q->qlength);
}

void Init_Queue(QUEUE *q)
{
	q->front = NULL;
	q->rear = NULL;
	q->qlength = 0;
}

BTNODE *De_Queue(QUEUE *q)
{
	QNODE *p;
	BTNODE *x;
	if(q->qlength!=0)
	{
		p = q->front;
		x = p->value;
		q->front = p->pNext;
		free(p);
		--(q->qlength);
		return x;
	}
	else
		return NULL;
}

int QueueEmpty(QUEUE *q)
{
	if(q->qlength==0)
		return 1;
	else
		return 0;
}

层序遍历:

void level_traverse(BTNODE *root)
{
	QUEUE q;
	BTNODE *p;
	p = root;
	Init_Queue(&q);
	En_Queue(&q,p);
	while(!QueueEmpty(&q))
	{
		p = De_Queue(&q);
		printf("%c",p->data);
		if(p->lchild)
			En_Queue(&q,p->lchild);
		if(p->rchild)
			En_Queue(&q,p->rchild);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值