传送门:HDU 3999
题意
给出一组数, 按照bst树构建, 输出字典序最小得可构成相同bst树的序列
二分查找树
题解
BST构建, 根据bst树的特性, 构造时只要先插入中间结点就可确定树的形状
ex: 构造树2, 3, 1按2, 1, 3次序输入是相同的结果
所以先构造然后树的先序遍历输出即可
AC code:
/*
adrui's submission
Language : C++
Result : Accepted
Love : yy
Favorite : Dragon Balls
Standing in the Hall of Fame
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
#include<bitset>
#include<map>
#include<cctype>
using namespace std;
#define M(a, b) memset(a, b, sizeof(a))
#define mid ((l + r) >> 1)
#define ls rt << 1, l, mid
#define rs rt << 1|1, mid + 1, r
#define lowbit(x) (x & (-x))
#define LL long long
#define REP(n) for(int i = 0; i < n; i++)
#define debug 0
const int maxn(4000005); //最大节点数
int n, cnt;
struct BST {
BST *lch, *rch;
int key;
BST(int key = 0) {
this->key = key;
lch = rch = NULL;
}
void preorder() {
if (cnt++) cout << " ";
cout << key;
if (lch != NULL) lch->preorder();
if (rch != NULL) rch->preorder();
}
void insert(int key) {
BST *rt = this, *tmp = new BST(key);
while (rt->key) {
if (tmp->key < rt->key) {
if (rt->lch == 0)
rt->lch = new BST;
rt = rt->lch;
}
else {
if (rt->rch == 0)
rt->rch = new BST;
rt = rt->rch;
}
}
rt->key = tmp->key;
}
};
int main() {
#if debug
freopen("in.txt", "r", stdin);
#endif //debug
cin.tie(0);
cin.sync_with_stdio(false);
int a;
while (cin >> n) {
BST rt;
cnt = 0;
for (int i = 0; i < n; ++i) {
cin >> a;
rt.insert(a);
}
rt.preorder();
cout << endl;
}
return 0;
}