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
| #include<stdio.h> #include<malloc.h> #include<stdlib.h>
#define maxsize 10 typedef int datatype; typedef struct node { datatype data; struct node *lchild,*rchild; } bitree;
bitree* CreatBitree(int* arrayA,int n); void preorder(bitree *p); void midorder(bitree *p); void postorder(bitree *p);
void main() { int arrayA[9]={0,1,2,3,4,5,6,7,8}; int n=sizeof(arrayA)/sizeof(int);
bitree *head=NULL;
head=CreatBitree(arrayA,n);
printf("前序遍历:"); preorder(head); printf("\n中序遍历:"); midorder(head); printf("\n后序遍历:"); postorder(head); 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; }
void preorder(bitree *p) { if(p!=NULL) { printf("%d ",p->data); preorder(p->lchild); preorder(p->rchild); } return; }
void midorder(bitree *p) { if(p!=NULL) { midorder(p->lchild); printf("%d ",p->data); midorder(p->rchild); } return; }
void postorder(bitree *p) { if(p!=NULL) { postorder(p->lchild); postorder(p->rchild); printf("%d ",p->data); } return; }
|