采用层次遍历的算法,将所有结点加入队列(包括空结点)。当遇到空结点时,查看其后是否有非空结点。若有,则二叉树不是完全二叉树。
bool Judge_Complete_1(TNode* p)
{
Queue Q;
InitQueue(Q);
if(p==NULL)
return true;
EnQueue(Q,p);
while(QueueEmpty(Q)!=true)
{
DeQueue(Q,p);
if(p!=NULL)
{
EnQueue(Q,p->lchild);
EnQueue(Q,p->rchild);
}
else
{
while(QueueEmpty(Q)!=true)
{
DeQueue(Q,p);
if(p!=NULL)
return false;
}
}
}
return true;
}
我还写了一个递归算法,但是我不知道对不对。
bool Judge_Complete(TNode* p)
{
if(p==NULL)
return true;
if(p->lchild==NULL&&p->rchild!=NULL)
return false;
bool l=Judge_Complete(p->lchild);
bool r=Judge_Complete(p->rchild);
return l&&r;
}
转载:https://blog.csdn.net/qq_34941153/article/details/101835015
查看评论