E - The order of a Tree

题目:

As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely: 
1.  insert a key k to a empty tree, then the tree become a tree with 
only one node; 
2.  insert a key k to a nonempty tree, if k is less than the root ,insert 
it to the left sub-tree;else insert k to the right sub-tree. 
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape. 

Input

There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n. 

Output

One line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic. 

Sample Input

4

1 3 4 2

Sample Output

1 3 2 4

题意:

给你一个二叉树,让你输出二叉树的先序遍历:

思路:

再输入树的时候,把数据插入树中,建立一个二叉搜索树,同时用两个数组进行存储左右子树,然后找出先序顺序;

这道题是肯定要用到递归的;

代码如下:

#include<stdio.h>
#include<string.h>
#define N 100010

int t[N],l[N],r[N],a[N];
int flag,n,m;

void insert(int x,int y)
{
    if(y<=t[x])
    {
        if(l[x])
            insert(l[x],y);//接着判断;
        else
            l[x]=flag;//找到空处,就插入;
    }
    else
    {
        if(r[x])
            insert(r[x],y);//接着判断;
        else
            r[x]=flag;//找到空处,就插入;
    }
}

void xx(int x)//先序遍历;
{
    a[m++]=t[x];//先根
    if(l[x])
        xx(l[x]);//后左子树;
    if(r[x])
        xx(r[x]);//最后右子树;
}

int main()
{
    while(~scanf("%d",&n))
    {
        memset(l,0,sizeof l);
        memset(r,0,sizeof r);
        int root=-1;
        int i,x;
        flag=0;
        for(i=0; i<n; i++)
        {
            scanf("%d",&x);
            if(root==-1)//树根;
                t[++root]=x;
            else
            {
                t[++flag]=x;//建树;
                insert(root,x);
            }
        }
        m=0;
        xx(root);//寻找先序遍历;
        printf("%d",a[0]);//注意输出格式;
        for(i=1;i<m;i++)
            printf(" %d",a[i]);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/titi2018815/article/details/82082902