http://acm.hdu.edu.cn/showproblem.php?pid=3999
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.
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<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 100005
int a[maxn];
typedef struct Node
{
int key;
Node *left,*right;
}node;
node* create(node *t,int key) //递归建树
{
if(!t)
{
t=(node *)malloc(sizeof(node));
t->key=key;
t->left=NULL;
t->right=NULL;
}
else if(key>t->key)
t->right=create(t->right,key);
else if(key<t->key)
t->left=create(t->left,key);
return t;
}
int first=1;
void priority(node *t) //先序遍历
{
if(t!=NULL)
{
if(first)
{
first=0;
printf("%d",t->key);
}
else
printf(" %d",t->key);
priority(t->left);
priority(t->right);
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
node *root;
root=(node *)malloc(sizeof(node));
root->key=a[0];
root->left=NULL;
root->right=NULL;
for(i=1;i<n;i++)
create(root,a[i]);
priority(root);
printf("\n");
}
return 0;
}
题目