二叉搜索树的后序遍历序列

https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&from=cyc_github&tab=answerKey

class Solution {
public:
    bool helper(vector<int>::iterator itbegin, vector<int>::iterator itend){
        if(itend - itbegin  <= 2) return true;
        int root = *(itend-1);
        //left
        auto rs = itend-1;
        for(auto it = itbegin;it!=itend;++it){
            if(*it > root){
                rs = it;
                break;
            }
        }
        for(auto it = rs;it!=itend;++it){
            if(*it < root){
                return false;
            }
        }
        return helper(itbegin, rs) && helper(rs, itend-1);
    }
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.empty()) return false;
        return helper(sequence.begin(), sequence.end());
    }
};
posted @ 2021-03-28 14:38  rxh1999  阅读(44)  评论(0编辑  收藏  举报