Sword refers to offer--24. Post-order traversal sequence of binary search tree

Question: Input an integer array to determine whether the array is the result of subsequent traversal of a binary search tree, if so, return true, otherwise return false, assuming that any two numbers in the input array are different from each other, eg: input array { 5,7,6,9,11,10,8}, it returns true, because this integer sequence is the result of the post-order traversal of the binary search tree shown in the figure


Analysis: In the sequence obtained by the subsequent traversal of the binary search tree, the last number is the value of the root node of the tree. The previous numbers in the array can be divided into two parts. The first part is the value of the left subtree node. The node is small, the second part is the value of the right subtree node, they are all larger than the root node, which can be implemented by recursion

public class wr24verifyBST {
	public static boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length==0){
            return false;
        }
        if(sequence.length==1){
            return true;
        }
        return judge(sequence,0,sequence.length-1);
    }
    public static boolean judge(int [] arr,int start,int end){
        if(start>=end){
            return true;
        }
        int root=arr[end];//The last post-order traversal is the root node
        int index;
        for(index=start;index<end && arr[index]<root;index++);//Find the first value greater than the root node, that is, the right subtree
        for(int i=index;i<end;i++){
            if(arr[i]<root){//If there is a node in the right subtree that is smaller than the root node, return false
                return false;
            }
        }
        return judge(arr,start,index-1)&&judge(arr,index,end-1);
    }
    public static void main(String [] args){
    	int []a={5,7,6,9,11,10,8};
    	int []b={7,4,6,5};
    	boolean result=VerifySquenceOfBST(a);
    	System.out.println(result);
    	System.out.println(VerifySquenceOfBST(b));
    }
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325569136&siteId=291194637