1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #include<stdio.h> #include<stdlib.h> #include<malloc.h>
#define maxsize 20
typedef int datatype; typedef struct node { datatype data; struct node *lchild,*rchild; }bitree;
void Layer(bitree *p); bitree* CreatBitree(int* arrayA,int n); int countleaf(bitree *p); int treedepth(bitree*p,int l);
void main() { int arrayA[10]={0,1,2,3,4,5,6,7,8,9}; int n=sizeof(arrayA)/sizeof(int); int l=0; bitree *head=NULL;
head=CreatBitree(arrayA,n);
printf("二叉树的叶子数为:%d",countleaf(head)); printf("\n"); printf("二叉树的深度为: %d",treedepth(head,l)); printf("\n"); printf("按广度优先搜索遍历的结果为:");
printf("\n");
}
bitree* CreatBitree(int* arrayA,int n) { bitree *root; bitree *queue[maxsize]; bitree *p; int front,rear; front=1;rear=0; root=NULL;
for(int i=1;i<n;i++) { p=(bitree*)malloc(sizeof(bitree)); p->data=arrayA[i]; p->lchild=NULL; p->rchild=NULL;
rear++; queue[rear]=p;
if(rear==1) root=p; else { if(i%2==0) queue[front]->lchild=p; else { queue[front]->rchild=p; front=front+1; } }
}
return root; }
int countleaf(bitree *p) { static int count=0; if(p!=NULL) { count=countleaf(p->lchild); if((p->lchild==NULL)&&(p->rchild==NULL)) count=count+1; count=countleaf(p->rchild); } return count; }
int treedepth(bitree*p,int l) { static int h=0; if(p!=NULL) { l++; if(l>h) h=l; h=treedepth(p->lchild,l); h=treedepth(p->rchild,l); } return h; }
|