hdu 3999 The order of a Tree

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

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章