Article Directory
33 is inscribed: subsequent binary search tree traversal sequence
One, Title Description
Enter an integer array, the array is not the result of the determination after traversing a binary search tree. If it returns true, otherwise false. Suppose the input array of any two numbers are different from each other.
For example, the input array 5,7,6,9,11,10,8 {} Returns true, because the integer sequence after the binary search tree in preorder the results of FIG.
If the input array is {7,4,6,5}, since none of the trees, binary search tree traversal order of the sequence, thus returns false.
Second, the problem analysis
Postorder traversal order is: left subtree -> right subtree -> root (root last traversal)
Value based on the characteristics of the binary search tree, left subtree of node <root value <the right subtree of a node
array} {5,7,6,9,11,10,8
The above can be said combined digital array after traversing Binary Tree root last number, the remaining digits, the number is less than the root node (i.e., a left subtree part) are the top surface, a number greater than the root node (i.e., the right subtree portion) are at the back.
Third, questions
public boolean verifySquenceOfBST(int[] sequence) {
if(sequence== null || sequence.length<=0) {
return false;
}
return verifyCore(sequence, 0, sequence.length-1);
}
private boolean verifyCore(int[] sequence,int start,int end) {
if(start >= end) {
return true;
}
//判断左子树
int mid=start;
while(sequence[mid]<sequence[end]) {
mid++;
}
//判断右子树
for(int i=mid;i<end;i++) {
if(sequence[i]<sequence[end]) {
return false;
}
}
return verifyCore(sequence, start, mid-1)&&verifyCore(sequence, mid, end-1);
}