编写算法判别给定二叉树是否为完全二叉树。
要求实现下列函数:
Status CompleteBiTree(BiTree bt);
/* judge if the binary tree whose root is bt */
/* is a complete tree. */
二叉链表类型定义:
typedef struct BiTNode {
TElemType data;
BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
可用队列类型Queue的相关定义:
typedef BiTree QElemType; // 设队列元素为二叉树的指针类型
Status InitQueue(Queue &Q);
Status EnQueue(Queue &Q, QElemType e);
Status DeQueue(Queue &Q, QElemType &e);
Status GetHead(Queue Q, QElemType &e);
Status QueueEmpty(Queue Q);
Status CompleteBiTree(BiTree bt)
/* judge if the binary tree whose root is bt */
/* is a complete tree. */
{
Queue q;
InitQueue(q);
BiTree pb=bt;
int flag=0;
if(!bt)
return TRUE;
EnQueue(q,pb);
while(!QueueEmpty(q)&&flag==0){
DeQueue(q,pb);
if(pb){
EnQueue(q,pb->lchild);
EnQueue(q,pb->rchild);
}
else
flag=1;
}
while(!QueueEmpty(q)){
DeQueue(q,pb);
if(pb)
flag=0;
}
if(flag==0)
return FALSE;
return TRUE;
}