原题链接:
https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805440976633856&page=0
注意点:
- 这里的代码在PAT能过,AcWing会出现超时的测试点。
代码:
#include <iostream>
#include <vector>
using namespace std;
#define endl '\n'
int N;
struct treeNode {
int val;
treeNode* left;
treeNode* right;
};
treeNode* root;
int value[1000];
bool isBST;
bool isMirror;
bool isBSTPre(int left,int right) {//左闭右开
int rootVal = value[left];
int pos = left + 1;
if (left >= right) {
return true;
}
while (value[pos] < rootVal&&pos<N) {
pos++;
}
int pos1 = pos;
while (value[pos1] >= rootVal&&pos1<N) {
pos1++;
}
if (pos == N || pos1 == N) {
return isBSTPre(left + 1, pos) && isBSTPre(pos, pos1);
}
else {
return false;
}
}
bool isMirrorPre(int left, int right) {
int rootVal = value[left];
int pos = left + 1;
if (left >= right) {
return true;
}
while (value[pos] >= rootVal && pos < N) {
pos++;
}
int pos1 = pos;
while (value[pos1] < rootVal && pos1 < N) {
pos1++;
}
if (pos == N || pos1 == N) {
return isMirrorPre(left + 1, pos) && isMirrorPre(pos, pos1);
}
else {
return false;
}
}
void bstInsert(treeNode*& now, int x) {
if (now == NULL) {
now = new treeNode;
now->val = x;
now->left = NULL;
now->right = NULL;
return;
}
if (x < now->val) {//插入左子树
bstInsert(now->left, x);
}
else {//插入右子树
bstInsert(now->right, x);
}
}
void mirrorInsert(treeNode*& now, int x) {
if (now == NULL) {
now = new treeNode;
now->val = x;
now->left = NULL;
now->right = NULL;
return;
}
if (x >= now->val) {//插入左子树
mirrorInsert(now->left, x);
}
else {//插入右子树
mirrorInsert(now->right, x);
}
}
int x = 0;
void postTraversal(treeNode *now) {
if (now == NULL) {
return;
}
else {
postTraversal(now->left);
postTraversal(now->right);
if (x != 0) {
cout << " ";
}
cout << now->val;
x++;
}
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> N;
for (int i = 0; i < N; i++) {
cin >> value[i];
}
isBST=isBSTPre(0,N);
if (!isBST) {
isMirror=isMirrorPre(0,N);
}
if (isBST || isMirror) {
cout << "YES" << endl;
if (isBST) {
for (int i = 0; i < N; i++) {
bstInsert(root,value[i]);
}
}
else {
for (int i = 0; i < N; i++) {
mirrorInsert(root, value[i]);
}
}
postTraversal(root);
}
else {
cout << "NO" << endl;
}
return 0;
}