408之cpp(二叉树的广度优先遍历)

       二叉树的广度优先遍历(又称层序遍历)需要使用队列(通常用链表实现)来完成。以下是实现的代码,分为三个文件:function.h、queue.cpp 和 main.cpp。

1.function.h

#include<stdio.h>
#include<stdlib.h>
//二叉树的函数声明
typedef char elemtype;
typedef struct bitree {
	elemtype tdata;
	struct bitree* lchild, * rchild;
}bitree, * pbitree;
typedef struct tag {
	pbitree p;//指向某一个二叉树指针
	struct tag* next;
}tag, * ptag;

//辅助队列函数声明
typedef struct node{
	pbitree data;
	struct node *next;
}node;
typedef struct sq_queue {
	node* front, * rear;
}sq_queue;
void init_queue(sq_queue& Q);
bool is_empty(sq_queue Q);
void en_queue(sq_queue &Q,pbitree x);
void de_queue(sq_queue &Q, pbitree &keep);

2.queue.cpp(辅助队列的实现)

#include"function.h"
void init_queue(sq_queue& Q)
{
	Q.front = Q.rear = (node*)calloc(1, sizeof(node));
	Q.front->next = NULL;
}
bool is_empty(sq_queue Q)
{
	if (Q.rear == Q.front)
	{
		return true;
	}
	return false;
}
void en_queue(sq_queue &Q,pbitree x)
{
	node* s = (node*)calloc(1, sizeof(node));
	s->data = x;
	s->next = NULL;
	Q.rear->next = s;
	Q.rear = s;
}
void de_queue(sq_queue& Q, pbitree& keep)
{
	node* p = Q.front->next;
	keep = p->data;
	Q.front->next = p->next;
	if (Q.rear == p)
	{
		Q.rear = Q.front;
	}
	free(p);
}

3.main.cpp(层序遍历的实现)

#include"function.h"
void level_order(pbitree tree)
{
	sq_queue Q;
	init_queue(Q);
	pbitree keep;
	en_queue(Q, tree);//将根节点入队
	while (!is_empty(Q))
	{
		de_queue(Q,keep);
		putchar(keep->tdata);
		if (keep->lchild != NULL)
		{
			en_queue(Q, keep->lchild);//将左孩子入队
		}
		if (keep->rchild != NULL)
		{
			en_queue(Q, keep->rchild);//将右孩子入队
		}
	}
}
int main()
{
	//二叉树建树
	pbitree pnew;
	pbitree tree = NULL;
	elemtype c;
	ptag head = NULL, tail = NULL, pcur = NULL, link_new = NULL;
	while (scanf("%c", &c))
	{
		if (c == '\n')
		{
			break;
		}
		pnew = (pbitree)calloc(1, sizeof(bitree));
		pnew->tdata = c;
		link_new = (ptag)calloc(1, sizeof(tag));
		link_new->p = pnew;
		if (tree == NULL)
		{
			tree = pnew;
			head = link_new; tail = link_new;
			pcur = link_new; link_new = link_new;
			continue;
		}
		else
		{
			tail->next = link_new;
			tail = tail->next;
		}
		if (pcur->p->lchild == NULL)
		{
			pcur->p->lchild = pnew;
		}
		else if(pcur->p->rchild == NULL)
		{
			pcur->p->rchild = pnew;
			pcur = pcur->next;
		}

	}
	level_order(tree);//层序遍历(广度优先遍历)

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值