问题描述
输入一整数序列,建立二叉排序树,然后中序遍历。
输入说明
输入第一行为整数的个数n,第二行是具体的n个整数。
输出说明
建立二叉排序树,然后输出中序遍历的结果。
输入样例
5
1 6 5 9 8
输出样例
1 5 6 8 9
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int key;
struct node *lchild,*rchild;
}bst;
bst *root;
bst *insert(bst *t,bst *s)
{
bst *f,*p;
p=t;
while(p!=NULL)
{
f=p;
if(s->key==p->key) return t;
else if(s->key<p->key) p=p->lchild;
else p=p->rchild;
}
if(t==NULL) return s;
if(s->key<f->key) f->lchild=s;
else f->rchild=s;
return t;
}
bst *tree(int k[],int n)
{
int i;
bst *t,*s;
t=NULL;
for(i=0;i<n;i++)
{
s=(bst*)malloc(sizeof(bst));
s->lchild=NULL;s->rchild=NULL;
s->key=k[i];
t=insert(t,s);
}
return t;
}
void inorder(bst *p)
{
bst *stack[100];
bst *s;
s=p;
int top=-1;
while(top!=-1||s!=NULL)
{
while(s!=NULL)
{
top++;
stack[top]=s;
s=s->lchild;
}
s=stack[top];
top--;
printf("%d ",s->key);
s=s->rchild;
}
}
int main()
{
root=(bst*)malloc(sizeof(bst));
int n,i;
scanf("%d",&n);
int k[n];
for(i=0;i<n;i++) scanf("%d",&k[i]);
root=tree(k,n);
inorder(root);
return 0;
}