34、二叉搜索树的前序遍历序列(33题的衍生题)

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

class test  
{
    public static void main (String[] args) throws java.lang.Exception
    {
                // 测试用例
        //int[] sequence = new int[]{7,4,6,5};
        //int[] sequence = new int[]{};
        //int[] sequence = null;
        //int[] sequence = new int[]{15, 10, 8, 11, 18, 17, 19};
        //int[] sequence = new int[]{8,7,6,5};
        //int[] sequence = new int[]{8,9,10,11};
        //int[] sequence = new int[]{8};
        //int[] sequence = new int[]{8,7};
        //int[] sequence = new int[]{7,8};
        int[] sequence = new int[]{7,4,6,5,8,1};
        boolean result = VerifySquenceOfBST(sequence);
        System.out.println(result);
    }
    
    public static boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence==null || sequence.length==0) return false;
        if(sequence.length==1) return true;
        return verify(sequence, 0, sequence.length-1);
    }
    
    private static boolean verify(int[] sequence, int start, int end){
        if(start>=end) return true;
        int i=start+1;
        int rootVal = sequence[start];
        for(;i<=end;++i){
            if(sequence[i] > rootVal) break;
        }
        int j = i;
        for(;j<=end;++j){
            if(sequence[j]<= rootVal) return false;
        }
        return verify(sequence, start+1, i-1) && verify(sequence, i, end);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容