Python 二叉搜索樹的後序遍歷序列

輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入餓數組的任意兩個數字都互不相同。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def VerifySequenceOfBST(self, sequence):
        if sequence==[]:
            return False
        rootNum=sequence[-1]
        del sequence[-1]
        index=None
        for i in range(len(sequence)):
            if index == None and sequence[i]>rootNum:
                index=i
            if index!=None and sequence[i]<rootNum:
                return False
        if sequence[:index] ==[]:
            leftRet = True
        else:
            leftRet=self.VerifySequenceOfBST(sequence[:index])
        if sequence[index:]==[]:
            rightRet=True
        else:
            rightRet = self.VerifySequenceOfBST(sequence[index:])
        return leftRet and rightRet
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章