hdu 3999 The order of a Tree

来源:互联网 发布:手机做笔记软件 编辑:程序博客网 时间:2024/05/17 00:00

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 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

41 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;}


0 0
原创粉丝点击