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 2Sample Output
1 3 2 4
题目大意:已知一棵树,求一棵树和现在的树相同,但字典序最小。
思路: 二叉搜索树需要满足左儿子小于父节点,右儿子大于父节点,要求是同一棵树,所以应该根节点相同,先根后左最后右,即前序遍历。
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
vector<int>V;
struct node
{
int data;
node *lson;//左儿子
node *rson;//右儿子
node()//初始化
{
lson=NULL;
rson=NULL;
}
};
void inser(node *&root,int x)//BST插入函数
{
if(root==NULL)//遇到为NULL,即应该插入的位置
{
root=new node();//新建节点
root->data=x;//赋权值
return ;
}
if(root->data==x)//当前节点为插入的值,直接返回
return;
else if(root->data>x)//插入的值小于当前节点,需插入左子树
inser(root->lson,x);
else if(root->data<x)//插入的值大于当前节点,需插入右子树
inser(root->rson,x);
}
node *build()//BST建树********
{
node *root=NULL;
vector<int>::iterator it;//迭代器
for(it=V.begin(); it!=V.end(); it++)//依次插入树中
{
inser(root,*it);
}
return root;//返回的是根节点
}
void out(node *root,node *flag)//输出函数
{
if(root==NULL)//当访问的为空,即返回(递归的边界)
return ;
if(root!=flag)
printf(" ");
printf("%d",root->data);//输出当前节点的值
out(root->lson,flag);//访问左子树
out(root->rson,flag);//访问右子树
}
int main()
{
int n;
while(~scanf("%d",&n))
{
int x;
V.clear();//容器的清空
for(int i=0; i<n; i++)
{
scanf("%d",&x);
V.push_back(x);
}
node *root=build();
out(root,root);
printf("\n");
}
return 0;
}