/*
*完全二叉树的判定:对二叉树进行层次遍历,在遍历过程中对每一个结点进行检查:
* (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;
}
完全二叉树的判定
最新推荐文章于 2022-06-25 09:38:49 发布