33. 二叉搜索樹的後續遍歷序列(中等)

題目描述:

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

參考以下這顆二叉搜索樹:

     5
    / \
   2   6
  / \
 1   3
示例 1:
輸入: [1,6,3,2,5]
輸出: false
示例 2:
輸入: [1,3,2,6,5]
輸出: true

思路:暴力法

class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        # 二叉搜索樹中,左子樹都比根節點小;右子樹都比根節點大
        if not postorder:return True
        # 暴力法
        length=len(postorder)-1
        index=0
        while length:
            while index < length and postorder[index] < postorder[length]:
                index+=1
            while index < length and postorder[index] > postorder[length]:
                index+=1
            if index < length:
                return False
            index =0
            length -=1
        return True

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章