首页 > 其他 > 详细

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

时间:2020-06-20 00:42:29      阅读:105      评论:0      收藏:0      [点我收藏+]

题目描述

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出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);
    }
}

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

原文:https://www.cnblogs.com/ITxiaolei/p/13167098.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!