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
题意:
给出n个数,建立一个字典序最小的二叉搜索树,构成一颗相同的树。
左子树小右子树大,用题目给的序列建好二叉搜索树,然后输出他的前序遍历。
代码:
#include<stdio.h>
#include<string.h>
int n;
int mp[100050],ans[100050];
int ll[100050],rr[100050];
int l1,l2,num;
void lol(int l,int k)
{
if(mp[l]>=k)
{
if(ll[l])
lol(ll[l],k);
else
ll[l]=l2;
}
else
{
if(rr[l])
lol(rr[l],k);
else
rr[l]=l2;
}
}
void ss(int l)
{
ans[num++]=mp[l];
if(ll[l])
ss(ll[l]); //zuo
if(rr[l])
ss(rr[l]); //you
}
int main()
{
while(~scanf("%d",&n))
{
int k;
memset(ll,0,sizeof(ll));
memset(rr,0,sizeof(rr));
l1=-1,l2=0,num=0;
for(int i=0; i<n; i++)
{
scanf("%d",&k);
if(l1==-1)
mp[++l1]=k;
else
{
mp[++l2]=k;
lol(l1,k);
}
}
ss(l1);
for(int i=0; i<num-1; i++)
printf("%d ",ans[i]);
printf("%d\n",ans[num-1]);
}
return 0;
}
博客围绕二叉搜索树展开,指出其形状与插入键的顺序密切相关。任务是根据给定的树的插入顺序,找出能生成相同形状树且字典序最小的插入顺序。需用给定序列构建二叉搜索树,再输出其前序遍历。

被折叠的 条评论
为什么被折叠?



