您的位置:首页 > 其它

hdu 3999 The order of a Tree

2015-05-16 08:36 696 查看

The order of a Tree

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 withonly one node;2. insert a key k to a nonempty tree, if k is less than the root ,insertit 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 sequenceof 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<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;struct Tree{Tree *l,*r;  //建立树的左右子树int x;      //结点值};Tree *gen; //定义树Tree *jian(Tree *rt,int x) //建树{if(rt==NULL) //根{rt=(Tree *)malloc(sizeof(Tree)); //该结点是树根,则新开辟个结点,让其为根结点rt->x=x;rt->l=rt->r=NULL; //左右子树为空return rt;}if(rt->x>x) //如果当前的值小于结点的值,那么进入左子树{rt->l=jian(rt->l,x);}else rt->r=jian(rt->r,x); //如果当前的值大于结点的值,那么进入左右子树return rt;}void bianli(Tree *rt,int x) //遍历{if(x==1){cout<<rt->x;}else cout<<" "<<rt->x;if(rt->l!=NULL)  bianli(rt->l,2); //如果左子树不为空if(rt->r!=NULL) bianli(rt->r,2);//如果右子树不为空}int main(){int n,x;while(cin>>n){gen=NULL;for(int i=0;i<n;i++){cin>>x;gen=jian(gen,x);}bianli(gen,1);cout<<endl;}return 0;}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: