题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
python solution:
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
if len(sequence)==0:
return False
root = sequence[-1] #根节点的值
for i in range(len(sequence)): #记录左右子树的分割点
if sequence[i]>root:
break
for j in range(i,len(sequence)):
if sequence[j]<root:
return False
left,right = True,True
if i>0:
left = self.VerifySquenceOfBST(sequence[:i])
if i<len(sequence)-1:
right = self.VerifySquenceOfBST(sequence[i:len(sequence)-1])
return left and right