剑指offer:面试题24、二叉搜索树的后续遍历序列

题目描述

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

代码示例

public class Offer24 {
    public static void main(String[] args) {
        int[] postSeq = {1, 3, 2};
        Offer24 testObj = new Offer24();
        System.out.println(testObj.verifyPostSeqOfBST(postSeq));
    }

    public boolean verifyPostSeqOfBST(int[] seq) {
        if (seq == null || seq.length == 0)
            return false;
        return verifyPostSeqOfBST(seq, 0, seq.length - 1);
    }

    private boolean verifyPostSeqOfBST(int[] seq, int left, int right) {
        if (right - left <= 1) {
            return true;
        }
        int rootVal = seq[right];
        int curIndex = left;
        while (curIndex < right && seq[curIndex] <= rootVal)
            curIndex++;
        for (int i = curIndex; i < right; i++) {
            if (seq[i] < rootVal) {
                return false;
            }
        }
        return verifyPostSeqOfBST(seq, left, curIndex - 1)
                && verifyPostSeqOfBST(seq, curIndex, right - 1);
    }
}

猜你喜欢

转载自www.cnblogs.com/ITxiaolei/p/13167098.html
今日推荐