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.
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.
4 1 3 4 2
1 3 2 4
题意:构建二叉搜索树,输出按字典序最小的插入方式使得和构建的二叉搜索树一样;
思路:构建好二叉搜索树,直接输出前序遍历(要想插入和原图一样的话,只有先序遍历最小了,自己好好想想);
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define Max 100010
int f;
struct node
{
int tt;
node *left;
node *right;
node(int k)
{
tt = k;
left = NULL;
right = NULL;
}
};
node *insert(node *root,int k) // 插入值,构建二叉搜索树;
{
if(root==NULL)
{
node *pp = new node(k);
return pp;
}
else
{
if(k<root->tt)
root->left = insert(root->left,k);
else root->right = insert(root->right,k);
return root;
}
}
void prodfs(node *root) // 输出先序遍历;
{
if(root==NULL)
return ;
if(!f)
{
printf("%d",root->tt);
f=1;
}
else printf(" %d",root->tt);
prodfs(root->left);
prodfs(root->right);
}
int main()
{
int i,j,n;
while(~scanf("%d",&n))
{
node *root=NULL;
int k;
f=0;
for(i=0;i<n;i++)
{
scanf("%d",&k);
root = insert(root,k);
}
prodfs(root);
printf("\n");
}
return 0;
}