美文网首页
二叉搜索树的后序遍历序列

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

作者: momo1023 | 来源:发表于2019-03-27 18:13 被阅读0次
# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if not sequence:
            return False
        if len(sequence) <= 2:
            return True
        l = len(sequence)
        root = sequence[-1]
        # 注意此处应该是range(l),否则会错
        for i in range(l):
            if sequence[i] > root:
                break
        for val in sequence[i:-1]:
            if val < root:
                return False
        left = True
        right = True
        if i > 0:
            left = self.VerifySquenceOfBST(sequence[:i])
        if i < l - 1:
            right = self.VerifySquenceOfBST(sequence[i:-1])
        return left and right

相关文章

网友评论

      本文标题:二叉搜索树的后序遍历序列

      本文链接:https://www.haomeiwen.com/subject/jojtbqtx.html