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

题目描述

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

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        int length = sequence.size();
        if(length <= 2) return true;
        int root = length-1;
        int start = 0;
        int end = length-2;
        return Partion(sequence, start, end, root);
    }
    bool Partion(vector<int> sequ, int start, int end, int root)
    {
        if(start == end) return true;
        int i = start;
        int leftEnd = start - 1;
        while(i <= end)
        {
            if(sequ[i] < sequ[root])
            {
                leftEnd = i;
                i++;
            }
            else
                break;
        }
        while(i <= end)
        {
            if(sequ[i] < sequ[root])
                return false;
        }
        if(leftEnd > start+1)
            Partion(sequ, start, leftEnd-1, leftEnd);
        if(end > leftEnd+2)
            Partion(sequ, leftEnd+1, end-1, end);
        
        return true;
    }
};

 

 画图分析了搜索二叉树后序遍历的特点,但转化为代码的时候脑袋一团浆糊。。。。

书上代码

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        int length = sequence.size();
        if(length <= 0)
            return false;
        int* pSequ = &sequence[0];
        return partion(pSequ, length);
    }
    bool partion(int* pSequ, int length)
    {
        int root = *(pSequ + length - 1);
        // 在二叉搜索树中左子树节点小于根节点
        int i = 0;
        for(; i < length -1; i++)
        {
            if(*(pSequ+i) > root)
                break;
        }
        // 在二叉搜索树中右子树节点大于根节点
        int j = i;
        for(; j < length - 1; j++)
        {
            if(*(pSequ+j) < root)
                return false;
        }
        // 判断左子树是不是二叉搜索树
        bool left = true;
        if(i > 0)
            left = partion(pSequ, i);
        // 判断右子树是不是二叉搜索树
        bool right = true;
        if(i < length - 1)
            right = partion(pSequ+i, length-i-1);
        
        return (left && right);
    }
};

先假定左右子树为true,根据 i 的情况递归调用判断左右子树到底是否为true,最后return (left && right) (自己递归调用层次没弄清楚,返回这里出错了)。

猜你喜欢

转载自blog.csdn.net/eartha1995/article/details/81093763