c++代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 1010;
int l1[N], r1[N], w1[N], idx1;
int l2[N], r2[N], w2[N], idx2;
int root1, root2;
vector<int> pre, pre1, pre2, post;
void insert1(int& u, int x) {
if (!u) u = ++idx1, w1[u] = x;
else if (x < w1[u]) insert1(l1[u], x);
else insert1(r1[u], x);
}
void insert2(int& u, int x) {
if (!u) u = ++idx2, w2[u] = x;
else if (x < w2[u]) insert2(r2[u], x);
else insert2(l2[u], x);
}
void preorder1(int u) {
if (!u) return;
pre1.push_back(w1[u]);
preorder1(l1[u]);
preorder1(r1[u]);
}
void preorder2(int u) {
if (!u) return;
pre2.push_back(w2[u]);
preorder2(l2[u]);
preorder2(r2[u]);
}
void postorder1(int u) {
if (!u) return;
postorder1(l1[u]);
postorder1(r1[u]);
post.push_back(w1[u]);
}
void postorder2(int u) {
if (!u) return;
postorder2(l2[u]);
postorder2(r2[u]);
post.push_back(w2[u]);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
insert1(root1, x);
insert2(root2, x);
pre.push_back(x);
}
preorder1(root1);
preorder2(root2);
if (pre == pre1) {
cout << "YES" << endl;
postorder1(root1);
for (int i = 0; i < post.size(); i++) {
if (i == 0) cout << post[i];
else cout << " " << post[i];
}
}
else if (pre == pre2) {
cout << "YES" << endl;
postorder2(root2);
for (int i = 0; i < post.size(); i++) {
if (i == 0) cout << post[i];
else cout << " " << post[i];
}
}
else cout << "NO" << endl;
return 0;
}