剑指Offer33—二叉搜索树的后序遍历序列(java版)

题目描述:

标签:栈  树  二叉搜索树  递归  二叉树  单调栈

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

代码:

 思路分析:

1、后序遍历是“左-右-中”的顺序,二叉搜索树的定义:根节点的值大于它左子树的所有值,小于它右子树的所有值。

2、所以后序遍历数组的最后一个值是根节点,通过循环遍历,找到左右子树的分界下标,分界下标以前的所有数都小于根节点的值,分解下标以后的所有数都大于根节点的值。

3、递归查找,(first, curIndex - 1)和 (curIndex, last - 1)区间

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder == null || postorder.length == 0){
            return true;
        }
        return check(postorder, 0, postorder.length - 1);
    }

    public boolean check(int[] postorder, int first, int last){
        if(last - first <= 1){
            return true;
        }
        int rootValue = postorder[last];
        int curIndex = first;
        while(curIndex < last && postorder[curIndex] < rootValue){
            curIndex++;
        }
        for(int i = curIndex; i < last;i++){
            if(postorder[i] < rootValue){
                return false;
            }
        }
        return check(postorder, first, curIndex - 1) && check(postorder, curIndex, last - 1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值