利用函数返回值,判断子树是否是BST或者镜像BST,isBST返回是否是BST,isBST2返回是否是镜像BST,函数参数root为前序序列中根的位置,e为前序序列最后位置。post1记录是BST时的后续序列,post2记录是镜像BST时的后续序列:
#include<bits/stdc++.h>
using namespace std;
vector<int> pre;
vector<int> post1,post2;
bool isbst(int root,int e){
if(root>e) return true;
int i=root+1;
while(i<=e&&pre[i]<pre[root]) i++; //找到第一个比pre[root]大的元素
for(int j=i;j<=e;j++)
if(pre[j]<pre[root]) return false;
bool a=isbst(root+1,i-1);
bool b=isbst(i,e);
post1.push_back(pre[root]);
return (a&&b);
}
bool isbst2(int root,int e){
if(root>e) return true;
int i=root+1;
while(i<=e&&pre[i]>=pre[root]) i++;
for(int j=i;j<=e;j++)
if(pre[j]>=pre[root]) return false;//找到第一个比pre[root]小的元素
bool a=isbst2(root+1,i-1);
bool b=isbst2(i,e);
post2.push_back(pre[root]);
return (a&&b);
}
int main(){
int n;
scanf("%d",&n);
pre.resize(n);
for(int i=0;i<n;i++)
scanf("%d",&pre[i]);
bool a=isbst(0,n-1);
bool b=isbst2(0,n-1);
if(a||b){
printf("YES\n");
if(a){
printf("%d",post1[0]);
for(int i=1;i<post1.size();i++)
printf(" %d",post1[i]);
}else{
printf("%d",post2[0]);
for(int i=1;i<post2.size();i++)
printf(" %d",post2[i]);
}
}else printf("NO");
}