剑指Offer(23)______二叉搜索树的后序遍历序列

本文介绍了一种算法,用于判断一个整数数组是否为某二叉搜索树的后序遍历结果。通过递归方法检查数组是否符合二叉搜索树的特性,并提供两种实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。


class Solution {
public:
     
    bool check(vector<int>& s,int l,int r){
        if(r - l <= 2) return true;
        int index = l;
        while(s[index] < s[r]) index ++;
        for(int i =  index ; i < r ; i ++)
            if(s[i] < s[r]) return false;
        return check(s,l,index-1) && check(s,index,r-1);
    }
     
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.size() == 0) return false;         //鲁棒性: 判断序列是否为空
        return check(sequence,0,sequence.size()-1);
    }
};


class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        int size = sequence.size();
        if(0==size)return false;
 
        int i = 0;
        while(--size)
        {
            while(sequence[i++]<sequence[size]);
            while(sequence[i++]>sequence[size]);
 
            if(i<size)return false;
            i=0;
        }
        return true;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值