面试题33: 二叉搜索树的后续遍历序列

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

class Solution:
    def Binary_search_tree_subsequent_traversal(self, sequence):
        # write code here
        if not sequence or len(sequence) <= 0:
            return False
        root = sequence[-1]
        i = 0

        # 找出左小右大的分界点i,此时i属于右子树
        for node in sequence[:-1]:
            if node > root:
                break
            i += 1

        # 如果在右子树中有比根节点小的值,直接返回False
        for node in sequence[i:-1]:
            if node < root:
                return False

        # 判断左子树是否为二叉搜索树
        left = True
        if i > 0:
            left = self.Binary_search_tree_subsequent_traversal(sequence[:i])
        # 判断右子树是否为二叉搜索树
        right = True
        if i < len(sequence)-1:
            right = self.Binary_search_tree_subsequent_traversal(sequence[i:-1])

        return left and right
if __name__=="__main__":
    list = [2,4,3,7,10,9,6]
    solution = Solution()
    a = solution.Binary_search_tree_subsequent_traversal(list)
    print(a)

 

你可能感兴趣的:(面试题33: 二叉搜索树的后续遍历序列)