23. The subsequent binary search tree traversal sequence
problem:
Enter an integer array, the array is not the result of the determination after traversing a binary search tree. If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.
solve:
thought:
Sequence preorder, the last number is the root of the tree, in front of an array of numbers can be divided into two parts: The first part is the value of the left sub-tree nodes, the root node is smaller than the value; the second portion is a right value of the sub-tree nodes, the root node is greater than, respectively, before and behind the two parts is determined by the recursive meets the above principles.
python code:
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if(sequence==None or len(sequence)==0):
return False
n=len(sequence)
root=sequence[-1]
for i in range(n):
if(sequence[i]>root):
break
for j in range(i,n):
if(sequence[j]<root):
return False
left=True
if i>0:
left=self.VerifySquenceOfBST(sequence[0:i])
right=True
if(j<n-1):
right=self.VerifySquenceOfBST(sequence[i:n-1])
return left and right