1043. Is It a Binary Search Tree (25)-PAT甲级真题

利用函数返回值,判断子树是否是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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值