#include <stdio.h>
struct node{
node *lchild;
node *rchild;
int c;
}tree[100];
int loc;
node *creat(){//生成节点
tree[loc].lchild=tree[loc].rchild=NULL;
return &tree[loc++];//返回指针并处理下一节点
}
//递归先序遍历
void preorder(node *tree){
printf("%d ",tree->c);
if(tree->lchild!=NULL) preorder(tree->lchild);
if(tree->rchild!=NULL) preorder(tree->rchild);
}
//递归中序遍历
void inorder(node *tree){
if(tree->lchild!=NULL) inorder(tree->lchild);
printf("%d ",tree->c);
if(tree->rchild!=NULL) inorder(tree->rchild);
}
//递归后序遍历
void postorder(node *tree){
if(tree->lchild!=NULL) postorder(tree->lchild);
if(tree->rchild!=NULL) postorder(tree->rchild);
printf("%d ",tree->c);
}
//递归插入节点
node *insert(node *t,int x){
if(t==NULL){//该节点为空
t=creat();//生成一个新节点存放x
t->c=x;
return t;
}
else if(t->c<x)//插入的值比节点值大,插到右支树
t->rchild=insert(t->rchild,x);
else if(t->c>x)//插入的值比节点值小,插到左支树
t->lchild=insert(t->lchild,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);
}
preorder(t);
printf("\n");
inorder(t);
printf("\n");
postorder(t);
printf("\n");
}
return 0;
}
5
1 6 5 9 8
- insert有返回值t
- 函数返回指针 node *insert()