Examples prove safety offer 23. After concrete so abstract binary search tree sequence preorder

 

Title Description

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.
 
Problem-solving ideas: 

The idea of ​​using divide and conquer, to find the root node, the sequence left subtree, right subtree sequences, respectively judgment about whether the subsequent sub-sequence of binary sequence.

Available from the meaning of the questions:
1. postorder last element in the sequence of the root node of the binary tree;
2. A binary search tree in the left subtree of all nodes is less than the root node, all right subtree are greater than the root node.

Algorithm steps are as follows:
1. Locate the root node;
2. traversal sequence, the first to find a root element of greater than or equal i, the left side of the left subtree i, i on the right side of the right subtree;
3. We already know all the elements of the left side of i is less than root, then traverse to the right and then turn to see if all the elements are greater than the root; if the element is less than the root node appears, simply return false; if the right side all larger than the root, then:
4. Analyzing each recursive left / right sub-sequence is the sequence after sequence;
 

 

code show as below: 

 


 

package jianzhioffer.tree;

 

/ **
* enter an integer array, the array is not determined after traversing a binary search tree results.
* If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.
@Author Hadoop *
*
* /
public class VerifySquenceOfBST {

public Boolean VerifySquenceOfBST (int [] Sequence) {
IF (sequence.length ==. 1) {
return to true;
}
IF (sequence.length == 0) {
return to false;
}

return Judge (Sequence, 0,-sequence.length. 1);


}
public Boolean Judge (int [] A, Start int, int End) {
IF (Start> End) {
return to true;
}
int = the root A [End];
int Start = I;
the while (A [I] <the root) {
I ++;
}
Boolean Judge left = (A, Start,. 1-I);
int J = I;
while (j<end) {
if (a[j]<a[end]) {
return false;
}
j++;

}
boolean right=judge(a, i, end-1);


return left&&right;


}
}

 

 


 

 

 

 

Guess you like

Origin www.cnblogs.com/Transkai/p/10927183.html