PTA 甲级 1043 Is It a Binary Search Tree

#include
#define MAXN 1010
using namespace std;
int a[MAXN];
int flag=0;
vector ans;//后序序列
bool isMirror=false;
void postOrder(int left,int right){
    if(left>right) return;
    int root=a[left];
    int i=left+1,j=right;
    if(!isMirror){
        while(i<=right&&a[i]>=a[left]) i++;
        while(j>=left&&a[j]left&&a[j]>=a[left])j--;
    }
    if(i-j!=1) return;
    postOrder(left+1,i-1);
    postOrder(j+1,right);
    ans.push_back(root);
}

int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    postOrder(1,n);
    if(ans.size()==n) flag=1;
    else{
        ans.clear();
        isMirror=true;
        postOrder(1,n);
        if(ans.size()==n) flag=1;
    }
    if(flag){
        cout<<"YES"<

你可能感兴趣的:(PTA,算法,c++,数据结构)