您的位置:首页 > 其它

通过队列实现判断一棵二叉树是否为完全二叉树

2014-04-28 22:31 274 查看
要实现题目的功能,则需在用队列遍历层次遍历二叉树的代码基础上作修改

层次遍历二叉树代码如下void LevelOrder(BiTree bt, void (*visit)(TElemType))
/* travel BiTree bt by level, Return result by ss. */
{
if(!bt) return;
BiTree p=bt;
int i=0;
Queue Q;
InitQueue(Q);
if(p!=NULL)
{
EnQueue(Q,p);
while(!QueueEmpty(Q))
{
DeQueue(Q,p);
visit(p->data);
if(p->lchild!=NULL)
EnQueue(Q,p->lchild);
if(p->rchild!=NULL)
EnQueue(Q,p->rchild);
}
}
}然而在这段代码基础作修改上,我们将换另一种思维方式,即无论结点的左右孩子是否为空,都入队列,当二叉树不是完全二叉树时,则会遍历到空指针,代码如下:
Status CompleteBiTree(BiTree bt)
/* judge if the binary tree whose root is bt */
/* is a complete tree. */
{
if(!bt) return TRUE;
BiTree p=bt;
Queue Q;
int hasNullPointer=0;
InitQueue(Q);
if(p!=NULL)
{
EnQueue(Q,p);
while(!QueueEmpty(Q))
{
DeQueue(Q,p);
if(!p) hasNullPointer=1;
else if(hasNullPointer==1) return FALSE;
else{
EnQueue(Q,p->lchild); //无论结点的左右孩子是否为空,都入队列
EnQueue(Q,p->rchild);
}
}
}
return TRUE;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐