验证二叉搜索树的后序遍历序列

LCR 152. 验证二叉搜索树的后序遍历序列


class VerifyTreeOrder:
    """
    LCR 152. 验证二叉搜索树的后序遍历序列
    https://leetcode.cn/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/description/
    """
    def solution(self, postorder: List[int]) -> bool:
        return self.check(postorder, 0, len(postorder) - 1)

    # 检查postorder[i, j] 是否为BST
    def check(self, postorder, i, j):
        if i >= j:
            return True

        root = postorder[j]
        #  postorder[i..left) 是左⼦树,应该都⼩于 root
        left = i
        while left < j and postorder[left] < root:
            left += 1

        #  postorder[left..j) 是右⼦树,应该都大于 root
        right = left
        while right < j and postorder[right] > root:
            right += 1

        if right != j:
            return False

        # 递归检查左⼦树 [i..left) 和右⼦树 [left..j) 也符合 BST 的性质
        return self.check(postorder, i, left - 1) and self.check(postorder, left, j - 1)


你可能感兴趣的:(LeetCode,数据结构与算法,二叉树)