(1)判断是否为完全二叉树 (2)求二叉树的高度

欢迎加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;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值