www

导航

二叉搜索树的后序遍历序列

public boolean VerifySquenceOfBST(int[] sequence) {
    if(sequence == null || sequence.length==0) return false;
    int start = 0, end = sequence.length-1;
    return helper(sequence, start, end);
}

public boolean helper(int[] sequence, int start, int end){
    if(start >= end) return true;
    int index = end;
    while(index>=start && sequence[index]>=sequence[end]){
        index--;    
    }
    if(index!=start-1){
        for(int i=start; i<=index; i++){
            if(sequence[i]>sequence[end]) return false;    
        }
        for(int i=index+1; i<end; i++){
            if(sequence[i]<sequence[end]) return false;    
        }
    }
    
    return helper(sequence,start,index) && helper(sequence,index+1,end-1);
}

 

posted on 2019-02-28 19:35  www_practice  阅读(150)  评论(0编辑  收藏  举报