【LeetCode刷题(中等程度)】剑指 Offer 33. 二叉搜索树的后序遍历序列

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

参考以下这颗二叉搜索树:
在这里插入图片描述

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:后序遍历中最后一个节点为根,我们依次查看左子树和右子树是不是BST, 这里存在递归。

class Solution {
public:
    bool verifyPostorder(vector<int>& postorder) {
        int len = postorder.size();
        if (len == 0) {
            return true;
        }

        int i = 0;
        vector<int> postorder_lef, postorder_rig;
        for (;i < len - 1; i++) {
            if (postorder[i] > postorder[len - 1]) {
                break;
            }
            postorder_lef.emplace_back(postorder[i]);  // 从0 ~ i-1 共i个元素
        }
        int j = i;
        for (; j < len - 1; j++) {
            if (postorder[j] < postorder[len - 1]) {
                return false;
            }
            postorder_rig.emplace_back(postorder[j]);
        }
        bool left = true;
        if (i > 0) {  // 存在左子树时,进行递归校验,不存在,则左子树默认true
            left = verifyPostorder(postorder_lef);
        }
        bool right = true;
        if (i < len - 1) {  // 存在右子树时,进行递归校验,不存在,则右子树默认true
            right = verifyPostorder(postorder_rig);
        }
        return left && right;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33197518/article/details/108783000