Sword refers to offer ------ post-order traversal sequence of binary search tree

Insert picture description here

Topic link!
Idea: For
this question, we only need to know the characteristics of the binary search tree, the specific details are in the code, this question can also be changed to restore the original binary search tree, you can try to write.
Code:

class Solution {
    
    
public:
    //递归
    bool verifyPostorder(vector<int>& postorder) {
    
    
        if(postorder.empty())return true;
        return isBST(postorder, 0, postorder.size() - 1);  //我们把区间的下标表示当做参数比较好处理
    }
    bool isBST(vector<int>& post, int l, int r){
    
    //[l, r]表示当前区间,左闭右闭
        if(l >= r)return true;//穿过叶子结点返回true
        int flag = post[r];//flag存放当前树根节点的值
        int i = l;//从当前序列的左边界开始遍历
        for(; i < r; i ++ ){
    
    //找到第一个大于根节点值的位置
                            //将该节点到尾节点之前的区间( [该节点,尾节点),左闭右开)
                            //视为右子树对应的序列
            if(post[i] > flag)
                break;
        }
        for(int j = i + 1; j < r; j ++ ){
    
    //检查右子树对应序列中有无小于等于根节点值的节点
                                        //若有则表示该序列不可能为二叉搜索树对应的后序序列
            if(post[j] <= flag)
                return false;
        }
        //[l, i - 1]表示左子树, [i, r - 1]表示右子树
        return isBST(post, l, i - 1) && isBST(post, i, r - 1);//递归判断左子树及右子树
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114843215