剑指Offer23:二叉搜索树的后序遍历序列

思路:

已知条件后序序列最后一个值为root;二叉搜索树左子树值都比root小,右子树值都比root大。

1、确定root;

2、遍历序列(除去root结点),找到第一个大于root的位置,则该位置左边为左子树,右边为右子树;

3、遍历右子树,若发现有小于root的值,则直接返回false;

4、分别判断左子树和右子树是否仍是二叉搜索树(即递归步骤1、2、3)。

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        length = len(sequence)
        if length == 0:
            return False
        if length == 1:
            return True
        root = sequence[-1]
        index = 0
        while sequence[index] < root:
                index += 1
        for j in range(index, length-1):
            if sequence[j] < root:
                return False 
        left = sequence[:index]
        right = sequence[index:length-1]
         
        leftIs = True
        rightIs = True
          
        if len(left) > 0:
            leftIs = self.VerifySquenceOfBST(sequence=left)
        if len(right) > 0:
            rightIs = self.VerifySquenceOfBST(sequence=right)
        return leftIs and rightIs

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/84935821