计算二叉树的最大深度和最大宽度
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxSize 500
typedef struct BiTNode{
char data[5];
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct SqQueue{
BiTNode *t[MaxSize];
int rear,front;
}SqQueue;
int Length(BiTree T);
BiTNode *CreateBiTree();
int high(BiTree T);
int main(){
BiTNode *p=CreateBiTree();
int l=Length(p);
int h=high(p);
printf("the length:%d\nthe high:%d",l,h);
return 0;
}
BiTNode *CreateBiTree(){
BiTNode *T=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(T->data,"A");
BiTNode *p=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(p->data,"B");
T->lchild=p;
p=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(p->data,"C");
T->rchild=p;
p=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(p->data,"D");
T->lchild->lchild=p;
T->lchild->lchild->lchild=NULL;
T->lchild->lchild->rchild=NULL;
p=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(p->data,"E");
T->lchild->rchild=p;
T->lchild->rchild->lchild=NULL;
T->lchild->rchild->rchild=NULL;
p=(BiTNode *)malloc(sizeof(BiTNode));
strcpy(p->data,"F");
T->rchild->lchild=p;
T->rchild->lchild->lchild=NULL;
T->rchild->lchild->rchild=NULL;
T->rchild->rchild=NULL;
return T;
}
int Length(BiTree T){
SqQueue Q;
Q.rear=Q.front=0;
int lno[MaxSize];
int Lno=0,max=0,n;
BiTNode *p;
if(T){
Q.t[Q.rear]=T;
lno[Q.rear]=1;
Q.rear++;
while(Q.front!=Q.rear){
p=Q.t[Q.front];
Lno=lno[Q.front];
Q.front++;
if(p->lchild){
Q.t[Q.rear]=p->lchild;
lno[Q.rear]=Lno+1;
Q.rear++;
}
if(p->rchild){
Q.t[Q.rear]=p->rchild;
lno[Q.rear]=Lno+1;
Q.rear++;
}
}
for(int i=1;i<=Lno;i++){
n=0;
for(int j=0;j<Q.rear;j++){
if(lno[j]==i){
n++;
}
}
if(max<n){
max=n;
}
}
return max;
}else{
return 0;
}
}
int high(BiTree T){
int m,n;
if(T){
m=high(T->lchild);
n=high(T->rchild);
return m>n?m+1:n+1;
}else{
return 0;
}
}
程序运行截图:
|