33, after the sequence of binary search tree traversal

1, 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.

2, the idea: binary search tree is the value of the left subtree node is less than the value of the node, the value is greater than the value of the right subtree of the node. So for the sequence of the binary search tree, the root of the left and right traversal order, the last value in the array must be the root node, and depending on the nature of the binary search tree, is smaller than the value of the left sub-tree root, is greater than the value of the right subtree the root node, through front to back through the array, you can find the preliminary boundaries around sub-tree, before the cut-off must be left subtree, but after the cut-off can not guarantee that all values ​​are greater than the root, so to verify whether it is the right subtree . After calibration is completed, it is determined in the coarse-grained condition is met binary search tree, at which time the left and right subtree, respectively, into the iterative method, the whole tree to determine whether the binary search tree in full compliance with the fine-grained nature.

3, Code:

import java.util.*;
import java.lang.*;
public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        //鲁棒性校验
        if(sequence==null||sequence.length==0){
            return false;
        } 
        int length = sequence.length;
         // array last number is the value of root 
        int the root = Sequence [-length. 1 ];
        
        // left child node is less than the root, the right child node is greater than the root node, the left and right subtrees positioning boundaries
         // initial boundaries, but not necessarily to the right subtree binary search tree is defined 
        int I = 0 ;
         for (; I <Length- . 1; I ++ ) {
             IF (Sequence [I]> the root) {
                 BREAK ;
            }
        }
        
        // check whether the right subtree meet the definition of a binary tree, i.e., the whole is greater than the right subtree root 
        int J = I;
         for (; J <-length. 1; J ++ ) {
             IF (Sequence [J] < the root) {
                 return  to false ;
            }
        }
        
        // left internal tree recursively determines whether the sub binary search tree law 
        Boolean left = to true ;
         Boolean right = to true ;
         IF (I> 0 ) {
            left=VerifySquenceOfBST(Arrays.copyOfRange(sequence,0,i));
        }
         if(i<(length-1)){
            right=VerifySquenceOfBST(Arrays.copyOfRange(sequence,i,length-1));
        }
        return (left&&right);
    }
}

Guess you like

Origin www.cnblogs.com/guoyu1/p/12147976.html