二叉搜索树的后序遍历序列 牛客网 剑指Offer

牛客网 剑指Offer

  • 题目描述
  • 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
class Solution:
    #run:22ms memory:5852k
    def VerifySquenceOfBST(self,sequence):
        if sequence == []:
            return False
        if len(sequence) == 1:
            return True
        limit_index = -1
        for i in range(len(sequence)-1):
            if sequence[i] > sequence[-1]:
                limit_index = i
            elif sequence[i] < sequence[-1] and limit_index != -1:
                return  False
        if limit_index != 0 and limit_index != -1:
            left = self.VerifySquenceOfBST(sequence[:limit_index])
            right = self.VerifySquenceOfBST(sequence[limit_index:-1])
            return left and right
        else:
            sub = self.VerifySquenceOfBST(sequence[:-1])
            return sub

 

你可能感兴趣的:(Algorithm,算法,牛客网,剑指Offer)