首先我们需要借助到队列
我们有两种思路
思路一:我们将所有节点都入队列,空节点入队列,当我们取队首元素,取到空的时候。我们查看队列里面size是不是0,不是0的话判断一下,如果是空这个标记,那么我们出队列,如果遇到还有不是空标记的元素,那么就一定不是完全二叉树。如果没有,那么就是完全二叉树。
具体实现看代码
int iscompletetree(treenode *root)
{
if(root == NULL)
{
return;
}
seqqueue s;
treenode *top;
seqqueue_init(&s);
seqqueue_push(&s,root);
while(seqqueue_gettop(&s,&top))
{
seqqueue_push(&s,top->lchild);
seqqueue_push(&s,top->rchild);
seqqueue_pop(&s);
seqqueue_gettop(&s,&top);
}
seqqueue_pop(&s);
while(s.size != 0)
{
seqqueue_gettop(&s,&top);
if(top != NULL)
{
return 0;
}
seqqueue_pop(&s);
}
return 1;
}
思路二
将根节点入队列,取队首,出队列,进入阶段一
判断如果是有左右子树,那么把他们入队列,如果是没左有右,说明不是,如果有左无右,那么可以进入阶段二,并插入当前左子树,如果无左无右,也可以进入阶段二
二阶段如果左右都没子树,那么啥事不干,,否则就不是。循环完成后就说明是完全二叉树
int iscompletetree(treenode *root)
{
if(root == NULL)
{
return 0;
}
seqqueue q;
seqqueue_init(&q);
seqqueue_push(&q,root);
treenode *top = NULL;
int start_step_two = 0;
while(seqqueue_gettop(&q,&top))
{
seqqueue_pop(&q);
if(start_step_two == 0)
{
//阶段一
if(top->lchild != NULL && top->rchild != NULL)
{
seqqueue_push(&q,top->lchild);
seqqueue_push(&q,top->rchild);
}
else if(top->lchild == NULL && top->rchild != NULL)
{
return 0;
}
else if(top->lchild != NULL &&top->rchild == NULL)
{
start_step_two = 1;
seqqueue_push(&q,top->lchild);
}
else
{
start_step_two = 1;
}
}
else
{
if(top->lchild == NULL && top->rchild == NULL);
else
{
return 0;
}
}
return 1;
}
}