題目
輸入一個整數(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)
- 用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]
- for循環(huán)的break又被我忘了!以后這種盡量寫成while循環(huán);
- 第二個for循環(huán)是從index+1開始的。
- 最后的verifyend需要-1! 把根節(jié)點排除,不然的話會死循環(huán)。