Prove safety offer: subsequent binary search tree traversal sequence (recursively)

topic:

Enter an integer array, the array is not the result of the determination of a binary search tree (left <root <right) after traversing. If the output Yes, otherwise the output No. Suppose the input array of any two numbers are different from each other.

answer:

Recursively, as follows:

import java.util.*;
public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence==null||sequence.length==0){
            return false;
        }
        int root = sequence[sequence.length-1];
        int index = -1;
        //找到左右子树分割点
        for(int i=0;i<sequence.length-1;i++){
            if(sequence[i]>root){
                index = i;
                break;
            }
        }
        boolean left = true;
        boolean right = true;
        //有右子树
        if(index>-1){
            for(int i=index;i<sequence.length-1;i++){
                //如果右子树有比root小的数字,false
                if(sequence[i]<root){
                    return false;
                }
            }
            right = VerifySquenceOfBST(Arrays.copyOfRange(sequence,index,sequence.length-1));
        }
        if(index>0){
            //有左子树
            left = VerifySquenceOfBST(Arrays.copyOfRange(sequence,0,index));
        }
        
        return left&&right;
    }
}

 

Published 92 original articles · won praise 2 · Views 8403

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104882412