标签:
1 2 2 1 20
2 1 20
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int a[1000],n;
struct Tree
{
    int s;
    Tree *L,*R;
}*Root;
Tree *Creat()
{
    Tree *p;
    p=new Tree;
    p->L=NULL;
    p->R=NULL;
}
int KKK=0;
int middle(Tree *root)
{
    if(root!=NULL)
    {
        middle(root->L);
        if(KKK==0)
            KKK=1;
        else
            printf(" ");
        printf("%d",root->s);
        middle(root->R);
    }
}
void Build()
{
    Tree *root;
    Root->s=a[0];
    for(int i=1; i<n; i++)
    {
        root=Root;
        while(1)
        {
            if(a[i]<root->s)
            {
                if(root->L==NULL)
                {
                    Tree *p;
                    p=Creat();
                    p->s=a[i];
                    root->L=p;
                    break;
                }
                else
                    root=root->L;
            }
            else
            {
                if(root->R==NULL)
                {
                    Tree *p;
                    p=Creat();
                    p->s=a[i];
                    root->R=p;
                    break;
                }
                else
                    root=root->R;
            }
        }
    }
}
int main()
{
    while(~scanf("%d",&n)) //又多定义了局部变量n
    {
        KKK=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        Root=Creat();
        Build();
        middle(Root);
        printf("\n");
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/became_a_wolf/article/details/47726273