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

根据二叉搜索树的性质,根节点最小,那么后序遍历的最后一个元素一定是根节点也是最小的,比这个结点小的就是左子树,大的就是右子树,然后递归判断,如果还有元素没有被遍历到那么这个序列就不是正确的后序遍历

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.size() == 0)
            return false;
        return find(sequence, 0, sequence.size() - 1);
    }
    
    bool find(vector<int> sq,int left,int right){
        if(right - left < 1)
            return true;
        int root = sq[right];
        int l = left, r = right - 1;
        while(l < right - 1){
            if(sq[l] < root){
                l++;
            }
            else{
                break;
            }
        }
        while(r > left){
            if(sq[r] > root){
                r--;
            }
            else{
                break;
            }
        }
        if(r - l > 0)
            return false;
        return find(sq, left, r) && find(sq, l, right - 1);
    }
};

 

posted @ 2017-10-13 18:36  Deaglepc  阅读(244)  评论(0编辑  收藏  举报