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

2018/10/20 Offer 共 502 字,约 2 分钟

title

problem link

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

solution

public class Solution {
    private boolean isBst(int[] a,int left,int right){
        if(left>=right)
            return true;
        int i=left;
        while (i<right&&a[i]<a[right]){
            i++;
        } 
        for(int j=i;j<right;j++){
            if(a[j]<a[right]){
                return false;
            }
        }
        return isBst(a,left,i-1)&&isBst(a,i,right-1);
    }
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence==null||sequence.length==0) return false;
        return isBst(sequence,0,sequence.length-1);
    }
}

Search

    Table of Contents