剑指offer24 二叉搜索树的后序遍历序列

自己写的更简洁的代码

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        int length = sequence.size();
        if(length <= 0)
            return false;
        return VerifyCore(sequence,0,length-1);
    }
    bool VerifyCore(vector<int> sequence,int start,int end){
        if(start >= end)    一定要有大于,大于可以比免没有左子树这种bug
            return true;
        int index = end;      这个地方不要设成start,在找不到比end大的数时候,即没有右子树的时候,会报错
        for(int i = start;i < end;i++){
            if(sequence[i] > sequence[end]){
                index = i;
                break;
            }
        }
        for(int j = index;j < end;j++){
            if(sequence[j] < sequence[end])
                return false;
        }
        return VerifyCore(sequence,start,index-1)&&VerifyCore(sequence,index,end-1);
    }
};

考虑两种边界条件,没有左子树,没有右子树。

posted @ 2017-08-04 15:32  有梦就要去实现他  阅读(166)  评论(0编辑  收藏  举报