//二叉树的基本操作之—建立二叉排序树并遍历
#include<stdio.h>
#include<string.h>
struct Node{
Node *lchild;
Node *rchild;
int c;
}Tree[110];//静态数组
int loc;// 静态数组中被使用的元素个数
Node *create(){//申请未使用的结点
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc+1];
}
void postOrder(Node *T){//后序遍历
if(T->lchild!=NULL)
postOrder(T->lchild);
if(T->rchild!=NULL)
postOrder(T->rchild);
printf("%d ",T->c);
}
void inOrder(Node *T){//中序遍历
if(T->lchild!=NULL)
inOrder(T->lchild);
printf("%d ",T->c);
if(T->rchild!=NULL)
inOrder(T->rchild);
}
void preOrder(Node *T){//前序遍历
printf("%d ",T->c);
if(T->lchild!=NULL)
preOrder(T->lchild);
if(T->rchild!=NULL)
preOrder(T->rchild);
}
Node *Insert(Node *T,int x){//将数字x 插入到排序树中
if(T==NULL){//当前树为空
T=create();
T->c=x;
return T;
}
else if(x<T->c){//若x小于根结点数值
T->lchild=Insert(T->lchild,x);//插到左子树上
else if(x>T->c)
T->rchild=Insert(T->rchild,x);//插到右子树上
return T;
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
loc=0;
Node *T=NULL;
for(int i=0;i<n;i++){
int x;
scanf("%d",&x);
T=Insert(T,x);//插入到排序树中
}
printf("先序遍历:");
preOrder(T);
printf("\n");
printf("中序遍历:");
inOrder(T);
printf("\n");
printf("后序遍历:");
postOrder(T);
printf("\n");
}
return 0;
}