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:
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<vector>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
void check_max (int &a,int b) {a=max (a,b);}
void check_min (int &a,int b) {a=min (a,b);}
vector <int> v;
int n;
struct node {
int data;
node *leftchild,*rightchild;
node () {
leftchild=NULL;
rightchild=NULL;
}
};
void insert (node *&root,int data) {
if (root==NULL) {
root=new node ();
root->data=data;
return ;
}
else if (root->data==data) return ;
else if (data>root->data) insert (root->rightchild,data);
else if (root->rightchild,data) insert (root->leftchild,data);
return ;
}
node * build () {
node *root=NULL;
for (auto it:v) {
insert (root,it);
}
return root;
}
void pre_travel (node *root,int flag) {
if (root==NULL) return ;
if (flag==1) printf ("%d",root->data);
else printf (" %d",root->data);
pre_travel (root->leftchild,++flag);
pre_travel (root->rightchild,++flag);
return ;
}
int main () {
while (scanf ("%d",&n)!=EOF) {
v.clear ();
for (int i=1;i<=n;i++) {
int x; scanf ("%d",&x);
v.push_back (x);
}
node *root=build ();
pre_travel (root,1);
printf ("\n");
}
return 0;
}
HDU 3999 The order of a Tree (排序二叉树的先序遍历)
原文:https://www.cnblogs.com/hhlya/p/14184145.html