面試題33. 二叉搜索樹的后序遍歷序列

題目

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

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

     5
    / \
   2   6
  / \
 1   3

示例 1:

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

輸入: [1,3,2,6,5]
輸出: true

提示:

數(shù)組長度 <= 1000

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。

解法

首先后序遍歷最后一個是root,通過root劃分左子樹和右子樹。如果右子樹有比root小的值,就返回False。

class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        if not postorder : return True
        return self.verify(postorder,0,len(postorder)-1)

    def verify(self, postorder, start, end):
        if end - start <= 0 :return True
        index = end - 1
        for i in range(start, end):
            if postorder[i] > postorder[end]: 
                index = i
                break
            # if i == end: return False
        for i in range(index+1, end):
            if postorder[i] < postorder[end]:return False

        return self.verify(postorder, start,index) and self.verify(postorder, index ,end-1)


  1. 用while循環(huán)求解
class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        if not postorder : return True
        return self.verify(postorder,0,len(postorder)-1)

    def verify(self, postorder, start, end):
        if end - start <= 0 :return True
        index = start
        while postorder[index] < postorder[end]:
            index += 1
        sep = index    
        while postorder[index] > postorder[end]:
            index += 1
        return index == end and self.verify(postorder, start,sep-1) and self.verify(postorder, sep,end-1)

反思

特殊用例:

[null, 6, 5]

  1. for循環(huán)的break又被我忘了!以后這種盡量寫成while循環(huán);
  2. 第二個for循環(huán)是從index+1開始的。
  3. 最后的verifyend需要-1! 把根節(jié)點排除,不然的話會死循環(huán)。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容