劍指offer_二叉搜尋樹的後序遍歷序列
題目描述
輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的陣列的任意兩個數字都互不相同。
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence:
return False
if len(sequence)==1:
return True
length = len(sequence)
root = sequence[-1]
i = 0
while sequence[i]< root:
i+=1
k = i
for j in range(k,length-1):
if sequence[j]<root:
return False
left_s = sequence[:k]
right_s = sequence[k:length-1]
leftis = True
rightis = True
if len(left_s) > 0:
leftis = self.VerifySquenceOfBST(sequence=left_s)
if len(right_s) > 0:
rightis = self.VerifySquenceOfBST(sequence=right_s)
return leftis and rightis