(1)判斷是否爲完全二叉樹 (2)求二叉樹的高度

(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;

}

發佈了75 篇原創文章 · 獲贊 128 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章