欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
(1)判断是否为完全二叉树
(2)求二叉树的高度
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
typedef struct BiTNode{
char data; //数据域
struct BiTNode *lchild, *rchild; //左、右孩子指针
}BiTNode, *BiTree;
//队列
typedef struct {
BiTree *base; //初始化动态分配空间
int front;
int rear;
} SqQueue;
void InitQueue(SqQueue &Q){
//构造一个空队列
Q.base=(BiTree *)malloc(SIZE*sizeof(BiTree));
if (!Q.base) exit(0);
else
Q.front=Q.rear=0;
}
int QueueEmpty(SqQueue Q){
//判空
if (Q.rear==Q.front) return 1;
else
return 0;
}
void EnQueue(SqQueue &Q,BiTree e){
//插入元素e为Q的新的队尾元素
if ((Q.rear+1)%SIZE==Q.front)
exit(0);
else
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%SIZE;
}
void DeQueue(SqQueue &Q,BiTree &e){
// 删除Q的队头元素, 并用e返回其值
if ((Q.rear+1)%SIZE==Q.front)
exit(0);
else
e=Q.base[Q.front];
Q.front=(Q.front+1)%SIZE;
} //队列
void CreatBiTree(BiTree &bt){
//构造二叉树
char ch;
ch=getchar();
if(ch=='#')
bt=NULL;
else{
bt=(BiTree)malloc(sizeof(BiTNode));
bt->data=ch;
CreatBiTree(bt->lchild);
CreatBiTree(bt->rchild);
}
}
int Depth(BiTree bt){
//求二叉树的高度
int hl,hr;
if(!bt){
return 0;
}
else{
hl=Depth(bt->lchild)+1;
hr=Depth(bt->rchild)+1;
return hl>hr?hl:hr;
}
}
int Judge(BiTree bt){
//判断是否为完全二叉树
SqQueue Q;
BiTree p;
int flag=1;
if(bt){
InitQueue(Q);
EnQueue(Q,bt);
while(!QueueEmpty(Q)&&flag){
DeQueue(Q,p);
if(p){
EnQueue(Q,p->lchild);
EnQueue(Q,p->rchild);
}
else{
while(!QueueEmpty(Q)&&flag){
DeQueue(Q,p);
if(p){
flag=0;
}
}
}
}
return flag;
}
}
int main(){
int h;
BiTree bt;
printf("输入数据:\n");
CreatBiTree(bt);
h=Depth(bt);
printf("树的高度为:%d\n",h);
if(Judge(bt)){
printf("是完全二叉树\n");
}
else{
printf("不是完全二叉树\n");
}
return 0;
}