1. 程式人生 > >《劍指offer》【二叉搜尋樹的後序遍歷序列】

《劍指offer》【二叉搜尋樹的後序遍歷序列】

class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if len(sequence) == 0:
            return False
        else:
            root = sequence[-1]
            del sequence[-1]
            lefttree = []
            righttree =[]
            # 左子樹和右子樹分界
            splitindex = -1
            for i in range(len(sequence)):
                # 值小於根結點的歸為左子樹
                if sequence[i] < root:
                    lefttree.append(sequence[i])
                    splitindex = i
                else:
                    break
            for i in range(splitindex+1, len(sequence)):
                # 若右子樹部分有小於根結點的值,說明不是二叉搜尋樹
                if sequence[i] > root:
                    righttree.append(sequence[i])
                else:
                    return False
            if len(lefttree) <= 1:
                left = True
            else:
                # 遞迴判斷左子樹
                left = self.VerifySquenceOfBST(lefttree)
            if len(righttree) <= 1:
                right = True
            else:
                right = self.VerifySquenceOfBST(righttree)
            return left and right