完全二叉树的判定

/*
*完全二叉树的判定:对二叉树进行层次遍历,在遍历过程中对每一个结点进行检查:
*				   (1)如果当前结点没有右子树,则剩下的全部结点必须既没有左子树,又没有右子树;
*				   (2)如果当前结点有右子树,则它必须也有左子树.
*/
#include<stdio.h>
#include<stdlib.h>

typedef struct BiTNode
{
	char info;
	struct BiTNode *lchild;
	struct BiTNode *rchild;
}*BiTree;
typedef struct QNode
{
	BiTree info;
	struct QNode *link;
}QNode,*QueuePtr;
typedef struct LinkQueue
{
	QueuePtr f;
	QueuePtr r;
}*PLinkQueue;

PLinkQueue createEmptyQueue_link(void)
{
	PLinkQueue p_queue;

	p_queue=(PLinkQueue)malloc(sizeof(struct LinkQueue));
	if(NULL!=p_queue->f)
	{
		p_queue->f=NULL;
		p_queue->r=NULL;
	
	}
	else
		printf("\tout of space!\n");
	return p_queue;
}
bool isEmptyQueue_link(PLinkQueue p_queue)
{
	return p_queue->f==NULL;
}
void enQueue_link(PLinkQueue p_queue,BiTree bt)
{
	QueuePtr p;

	p=(QueuePtr)malloc(sizeof(struct QNode));
	if(NULL==p)
	{
		printf("\tout of space!\n");
		exit(-1);
	}
	else
	{
		p->info=bt;	//将信息写入数据域
		p->link=NULL;//填写新节点信息
		if(NULL==p_queue->f)
		{
			p_queue->f=p;
			p_queue->r=p;
		}
		else
		{
			p_queue->r->link=p;
			p_queue->r=p;
		}
	}
}
void deQueue_link(PLinkQueue p_queue)
{
	QueuePtr p;

	if(NULL==p_queue->f)
	{
		printf("\tEmpty Queue!\n");
		exit(-1);
	}
	else
	{
		p=p_queue->f;
		if(p_queue->f==p_queue->r)
			p_queue->r=NULL;
		p_queue->f=p_queue->f->link;
	}
}
BiTree top_link(PLinkQueue p_queue)
{
	if(isEmptyQueue_link(p_queue))
	{
		printf("\tEmptyQueue!\n");
		exit(-1);
	}
	return p_queue->f->info;
}
BiTree createBiTree(BiTree bt)//先序创建二叉树
{
	char ch;

	scanf("%c",&ch);
	if('#'==ch)
	{
		bt=NULL;
	}
	else
	{
		bt=(BiTree)malloc(sizeof(struct BiTNode));
		if(NULL==bt)
		{
			exit(-1);
		}
		bt->info=ch;//生成根结点
		bt->lchild=createBiTree(bt->lchild);//构造左右子树
		bt->rchild=createBiTree(bt->rchild);
	}
	return bt;
}
int levelOrder(BiTree bt)
{
	bool flag=true;
	bool bcomfine=false;
	PLinkQueue p_queue;

	p_queue=createEmptyQueue_link();
	if(NULL==bt)
	{
		printf("\tEmpty tree!\n");
		exit(-1);
	}
	while(!isEmptyQueue_link(p_queue))
	{
		enQueue_link(p_queue,bt);
		if(!bt->lchild&&bt->rchild)//当检查当某个接点只有右儿子时,则退出
			return flag=false;
		if(bcomfine&&(bt->lchild||bt->rchild))//如果当前结点有右子树,则它必须也有左子树
			return flag=false;
		if(NULL!=bt->lchild)
		{
			enQueue_link(p_queue,bt->lchild);
		}
		if(NULL!=bt->rchild)
		{
			enQueue_link(p_queue,bt->rchild);
		}
		else
			bcomfine=true;
	}
	return flag;
}
int main()
{
	BiTree bt=NULL;

	printf("请按先序遍历序列输入二叉树中各个结点的值(字符):\n");
	bt=createBiTree(bt);
	printf("\n\n");

	printf("<------ 判断是否为完全二叉树操作---->\n");
    if(levelOrder(bt))
        printf("该二叉树是完全二叉树!\n");
    else
        printf("该二叉树不是完全二叉树!\n");
	printf("\n\n");

	return 0;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值