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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值