团体程序设计天梯赛 L2-004 这是二叉搜索树吗? (25分)
题目链接:
L2-004 这是二叉搜索树吗? (25分)
思路:
非镜像和镜像需要分开单独进行搜索;
按非镜像/镜像规则将前序序列严格转化为后序序列,如果序列个数不足n个那说明不符合当前规则;
均不符合我们就输出NO;
代码:
#include<bits/stdc++.h>
using namespace std;
int n, a[1005];
vector<int> post;
void dfs(int l, int r, bool mir) {
if(l > r) return;
int x, y;
if(!mir) {
for(x = l + 1; a[x] < a[l] && x <= r; ++x);
for(y = x; a[y] >= a[l] && y <= r; ++y);
}
else {
for(x = l + 1; a[x] >= a[l] && x <= r; ++x);
for(y = x; a[y] < a[l] && y <= r; ++y);
}
if(x > l + 1) dfs(l + 1, x - 1, mir);
if(x < r + 1) dfs(x, y - 1, mir);
post.push_back(a[l]);
}
inline void check() {
if(post.size() == n) {
puts("YES");
cout << post[0];
for(int i = 1; i < n; i++) cout << ' ' << post[i];
exit(0);
}
}
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
dfs(1, n, false);
check();
post.clear();
dfs(1, n, true);
check();
puts("NO");
return 0;
}