Problem Description
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
Sample Output
普通的前序遍历题
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct TREE
{
struct TREE *l,*r;
int num;
} tree;
tree *creat(tree *t,int x)
{
if(t == NULL)
{
t = (tree*)malloc(sizeof(tree));
t->num = x;
t->l = t->r = NULL;
return t;
}
if(t->num > x)
t->l = creat(t->l,x);
else
t->r = creat(t->r,x);
return t;
}
void libian(tree *t,int x)
{
if(x == 1)
printf("%d",t->num);
else
printf(" %d",t->num);
if(t->l!=NULL)
libian(t->l,2);
if(t->r!=NULL)
libian(t->r,2);
}
int main()
{
int i,m,n;
tree *t = NULL;
while(~scanf("%d",&n))
{
for(i = 0;i<n;i++)
{
scanf("%d",&m);
t = creat(t,m);
}
libian(t,1);
printf("\n");
}
return 0;
}