输入一系列整数,建立二叉排序树,并进行先、中、后序遍历
代码:
1 #include<stdio.h> 2 #include<string.h> 3 struct Node{ 4 Node *lchild,*rchild; 5 int c; 6 }Tree[110]; 7 int loc; 8 Node *create(){ 9 Tree[loc].lchild=Tree[loc].rchild=NULL; 10 return &Tree[loc++]; 11 } 12 void postOrder(Node *T){//后序遍历 13 if(T->lchild!=NULL){ 14 postOrder(T->lchild); 15 } 16 if(T->rchild!=NULL){ 17 postOrder(T->rchild); 18 } 19 printf("%d",T->c); 20 } 21 void inOrder(Node *T){//中序遍历 22 if(T->lchild!=NULL){ 23 postOrder(T->lchild); 24 } 25 printf("%d",T->c); 26 if(T->rchild!=NULL){ 27 postOrder(T->rchild); 28 } 29 } 30 void preOrder(Node *T){//先序遍历 31 printf("%d",T->c); 32 if(T->lchild!=NULL){ 33 postOrder(T->lchild); 34 } 35 if(T->rchild!=NULL){ 36 postOrder(T->rchild); 37 } 38 39 } 40 Node *Insert(Node *T,int x){ 41 if(T==NULL){ 42 T=create(); 43 T->c=x; 44 return T; 45 } 46 else if(x<T->c){ 47 T->lchild=Insert(T->lchild,x); 48 } 49 else if(x>T->c){ 50 T->rchild=Insert(T->rchild,x); 51 } 52 return T; 53 } 54 int main(){ 55 int n; 56 while(scanf("%d",&n)!=EOF){ 57 loc=0; 58 Node *T=NULL; 59 for(int i=0;i<n;i++){ 60 int x; 61 scanf("%d",&x); 62 T=Insert(T,x); 63 } 64 preOrder(T); 65 printf(" "); 66 inOrder(T); 67 printf(" "); 68 postOrder(T); 69 printf(" "); 70 } 71 return 0; 72 }