这种题边界真的是每次都搞不清楚,我感觉现场估计也写不出来。
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int ismirror;
int pre[N];
vector<int> post;
void dfs(int root,int tail) {//最后一个
if (root > tail) return;
int i = root + 1;
int j = tail;
if (!ismirror) {//正常的二叉搜索树
while (i <= tail && pre[i] < pre[root]) {
i++;
}
while (j > root && pre[j] >= pre[root]) {
j--;
}
if (i-j != 1) return;//无法构成二叉搜索树
dfs(root + 1, j);
dfs(i, tail);
post.push_back(pre[root]);
}
else {
while (i <= tail && pre[i] >= pre[root]) {
i++;
}
while (j > root && pre[j] < pre[root]) {
j--;
}
if (i - j != 1) return;//无法构成二叉搜索树
dfs(root + 1, j);
dfs(i, tail);
post.push_back(pre[root]);
}
}
int main() {
int ssize;
cin >> ssize;
for (int i=0; i < ssize; i++) {
cin >> pre[i];
}
ismirror = 0;
dfs(0, ssize - 1);
if (post.size() != ssize) {//如果不镜像无法满足二叉搜索树
ismirror = 1;
post.clear();
dfs(0, ssize - 1);
}
if (post.size() == ssize) {
cout << "YES" << endl;
int flag = 0;
for (int i = 0; i < post.size(); i++) {
if (flag) cout << " ";
cout << post[i];
flag++;
}
}
else {
cout << "NO" << endl;
}
return 0;
}
参考自: https://www.cnblogs.com/l609929321/p/8486086.html
标签:pre,int,dfs,二叉,L2,004,post,root,ssize From: https://www.cnblogs.com/chengyiyuki/p/18106550