#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct node
{ ElemType data;
struct node *lch,*rch;
}Snode;
Snode *creat_bt();
void insertl(Snode *t,Snode *s);
void inorder(Snode *p);
main()
{ Snode *H; int k; char ch;
do { printf("\n\n\n");
printf("\n 1. 建立二叉排序树 ");
printf("\n 2. 中序遍历二叉树 ");
printf("\n 3. 结束程序运行 ");
printf("\n=======================================");
printf("\n 请输入你的选择( 1 , 2 , 3):"); scanf("%d",&k);
switch(k)
{ case 1:{ H=creat_bt();} break;
case 2:{ printf("\n 中序遍历输出: ");
inorder(H);} break;
case 3:{ } break;
}
}while(k!=3);
printf("\n 再见! ");scanf("%c",&ch);
}
/* 建立二叉排序树 */
Snode *creat_bt()
{ Snode *t0,*s;int n,i;ElemType k;
printf("\n n = ?");scanf("%d",&n );
t0=NULL;
for(i=1; i<=n; i++)
{ printf("\n %d key =?",i); scanf("%d",&k);
s=(Snode*)malloc(sizeof(Snode));
s->data=k; s->lch=NULL; s->rch=NULL;
insertl(t0,s); /* 调用插入函数 */
}
return(t0);
}
/* 在二叉排序树七中,插入一个结点 s 的递归算法 */
void insertl(Snode *t,Snode *s)
{ if(t==NULL) t=s;
else if(s->data<t->data)
insertl(t->lch,s ); /* 将 s 插入 t 的左子树 */
else insertl(t->rch,s); /* 将 s 插入 t 的右子树 */
}
/* 中根遍历二叉树 */
void inorder(Snode *p)
{ if(p!=NULL)
{ inorder(p->lch);
printf("%8d", p->data);
inorder(p->rch);
}
}