The order of a Tree
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
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
思路:
题意:
- 给定一个序列,建立一个二叉排序树,然后输出一个满足下列要求的序列:
- 按照该序列建树之后和原树一样
- 新建立的树字典序最小
分析:
- 与原树一样,则必为先序、中序、后序遍历的一种
- 二叉排序树的字典序最小,指树的层序遍历的字典序最小,即为前序遍历
方法:建树,输出前序遍历
AC代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
using namespace std;
struct node
{
int data;
node *lc;
node *rc;
};
int n;
int flag;
//建二叉排序树
void create(node *&root,int t)
{
if(root==NULL)
{
root=new node;
root->data=t;
root->lc=NULL;
root->rc=NULL;
}
else if(t< root->data) create(root->lc,t);
else create(root->rc,t);
}
//先序遍历
void preorder(node *root)
{
if(root)
{
if(flag!=0) cout<<" ";
cout<<root->data;
flag=1;
preorder(root->lc);
preorder(root->rc);
}
}
int main()
{
int key,n;
while(cin>>n)
{
int t;
node *root=NULL;
for(int i=0;i<n;i++)
{
cin>>t;
create(root,t);
}
flag=0;
preorder(root);
cout<<endl;
}
return 0;
}