您的位置:首页 > 其它

判断一棵二叉树是否是完全二叉树

2020-02-06 12:57 323 查看

层次遍历一个二叉树,扫描到某个结点左孩子或右孩子为空时即停止,检查此时队列内所有结点是否均为叶子结点

#include <stdio.h>
#include <malloc.h>
#define false 0
#define true 1

typedef int status;
typedef int elemtype;
typedef struct BiTNode {
elemtype data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

BiTree creat(){ //按扩展前序建二叉树;
BiTree t;int x;
scanf("%d",&x);
if (x==0) t = NULL;
else
{
t = (BiTree)malloc(sizeof(BiTNode));
t->data = x;
t->lchild = creat();
t->rchild = creat();
}
return t;
}

status judge(BiTree bt)
{//判断一个给定的二叉树是否是完全二叉树
if(bt == NULL)
{
printf("该二叉树是完全二叉树!\n");
return true;
}

else
{
BiTree qu[100]; int front = -1, rear = -1;
BiTree p;
qu[++rear] = bt;
while(front != rear)
{
p = qu[++front];
if(p->lchild !=NULL)
qu[++rear] = p->lchild;
if(p->rchild != NULL)
qu[++rear] = p->rchild;
if(p->lchild == NULL || p->rchild == NULL)
break;
}
while(front != rear)
{
p = qu[++front];
if(p->lchild != NULL || p->rchild != NULL)
{
printf("该二叉树不是完全二叉树!\n");
return false;
}
}
if(front == rear)
{
printf("该二叉树是完全二叉树!\n");
return true;
}

}

}

int main()
{
printf("正在按扩展前序建二叉树:\n");
BiTree bt = creat();
judge(bt);

return 0;
}

或者王道上的做法:层次遍历二叉树,将非空结点(包括空指针)入队,遇到空结点时,开始检查队其后是否有非空结点(即队列内是否有非空结点)(还是王道的简洁一点==)

#include <stdio.h>
#include <malloc.h>
#define false 0
#define true 1

typedef int status;
typedef int elemtype;
typedef struct BiTNode {
elemtype data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

BiTree creat(){ //按扩展前序建二叉树;
BiTree t;int x;
scanf("%d",&x);
if (x==0) t = NULL;
else
{
t = (BiTree)malloc(sizeof(BiTNode));
t->data = x;
t->lchild = creat();
t->rchild = creat();
}
return t;
}

status judge(BiTree bt)
{//判断一个给定的二叉树是否是完全二叉树
//层次遍历一个二叉树,扫描到空指针处即停止,检查此时队列内所有结点是否均为叶子结点
if(bt == NULL)
{
printf("该二叉树是完全二叉树!\n");
return true;
}

else
{
BiTree qu[100]; int front = -1, rear = -1;
BiTree p;
qu[++rear] = bt;
while(front != rear)
{
p = qu[++front];
if(p->lchild !=NULL || p->rchild != NULL)
{
qu[++rear] = p->lchild;
qu[++rear] = p->rchild;
}
else
{
while(front != rear)
{
p = qu[++front];
if(p!=NULL)
{
printf("该二叉树不是完全二叉树!\n");
return false;
}
}
}
}

printf("该二叉树是完全二叉树!\n");
return true;
}

}

void print(BiTree bt)
{
if (bt!=NULL)
{
printf ("%d", bt->data);
print(bt->lchild);
print(bt->rchild);
}
}

int main()
{
printf("正在按扩展前序建二叉树:\n");
BiTree bt = creat();
judge(bt);

return 0;
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
小白算法习题记录本 发布了68 篇原创文章 · 获赞 9 · 访问量 1万+ 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: