输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def compareTree(self,inOrder,sequence): 4 n = len(sequence) 5 if n == 0: 6 return True 7 if n == 1: 8 return True if inOrder[0] == sequence[0] else False 9 root1 = sequence[-1] 10 for i in range(n): 11 if inOrder[i] == root1: 12 break 13 in1 = inOrder[:i] 14 last1 = sequence[:i] 15 16 in2 = inOrder[i+1:] 17 last2 = sequence[i:n-1] 18 return self.compareTree(in1,last1) and self.compareTree(in2,last2) 19 20 21 def VerifySquenceOfBST(self, sequence): 22 n = len(sequence) 23 if n == 0: 24 return False 25 inOrder = sorted(sequence) 26 root1 = sequence[-1] 27 for i in range(n): 28 if inOrder[i] == root1: 29 break 30 in1 = inOrder[:i] 31 last1 = sequence[:i] 32 33 in2 = inOrder[i+1:] 34 last2 = sequence[i:n-1] 35 return self.compareTree(in1,last1) and self.compareTree(in2,last2) 36 # write code here