数组中前面的数字可以分为两部分:
- 第一部分是左子树节点的值,它们都比根节点的值小;
- 第二部分是右子树节点的值,它们都比根节点的值大
class Solution: def VerifySquenceOfBST(self, sequence): # write code here if not sequence: return False #找到跟节点 root = sequence[- 1] i = 0 #找到左子树和右子树的分界点 while i < len(sequence) - 1: if sequence[i] > root: break i += 1 for j in range(i,len(sequence)-1): if sequence[j] < root: return False left = True right = 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