Prove safety: subsequent binary search tree traversal sequence

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.

 

Example:

        8 
       /   \
      610 
   / \ / \
   57911 


Input: 5,7,6,9,11,10,8 
Output: to true

 

 

solution

The last element in the sequence is the root node binary search tree.

From left to right to find the root node in the sequence left subtree (smaller than the root), the right subtree (larger than the root).

  • If the root elements appear smaller than the right sub-tree, it is false.
  • Otherwise, left and right subtrees recursively.
Example: 5,7,6,9,11,10,8   

1 . Postorder last digit of the result is the value of the root node 8
 2. 8 pre smaller than three numbers 5,7,6, 8 left subtree of nodes; 9,11 number 3 , 8 large than 10, 8 is a right subtree of the node.
3. Similarly, the portion of each array determining the corresponding sub-tree in the same manner.

 

 

 

Code:

public class Solution {
    
    public static boolean verifySquenceOfBST(int[] sequence){
        if(sequence == null || sequence.length < 1){
            return false;
        }
        return verify(sequence, 0, sequence.length-1);
    }
         
    private static boolean verify(int[] sequence, int start, int end) {
        if(start>=end){
            return true;
        }
        
        int Val = Sequence [End];
         int I = Start;
         the while (I <= End) {
             IF (Sequence [I]> = Val) {   // left subtree of the root node should be less than 
                BREAK ; 
            } 
            I ++ ; 
        } 
        
        for ( int J = I; J <End; J ++ ) {
             IF (Sequence [J] <Val) {   // right subtree of the root node should be greater than 
                return  to false ; 
            } 
        } 
        
        return Verify (Sequence, Start,. 1-I) Verify && (Sequence, I,-End. 1 ); 
    } 

    public static void main(String[] args) {
        int[] List = {5,7,6,9,11,10,8};
//        int[] List = {7,4,6,5};

        boolean t = verifySquenceOfBST(List);
        System.out.println(t);
    }
}

 

Guess you like

Origin www.cnblogs.com/lisen10/p/11197645.html