Day20:剑指 Offer 33. 二叉搜索树的后序遍历序列

题目

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

代码实现

分治算法

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if (postorder == null || postorder.length == 1){
            return true;
        }
        return recur(postorder,0,postorder.length-1);
    }
    public boolean recur(int[] postorder,int begin,int end){
        if (begin >= end){
            return true;
        }
        int index = begin;
        //找到end节点的左子树,存边界为div,实际左子树是begin到div-1
        while (postorder[index] < postorder[end]){
            index++;
        }
        int div = index;
        //index遍历结束一定是等于end,不然证明右子树中间有节点小于end节点的值,就不是二叉搜索树
        while (postorder[index] > postorder[end]){
            index++;
        }
        //从end节点的左子树和右子树分别遍历
        return index == end && recur(postorder,begin,div-1) && recur(postorder,div,end-1);
    }
}

单调栈

大佬思路

class Solution {
    public boolean verifyPostorder(int[] postorder) {
    Stack<Integer> stack = new Stack<>();
    int parent = Integer.MAX_VALUE;
    //注意for循环是倒叙遍历的
    for (int i = postorder.length - 1; i >= 0; i--) {
        int cur = postorder[i];
        //当如果前节点小于栈顶元素,说明栈顶元素和当前值构成了倒叙,
        //说明当前节点是前面某个节点的左子节点,我们要找到他的父节点
        while (!stack.isEmpty() && stack.peek() > cur)
            parent = stack.pop();
        //只要遇到了某一个左子节点,才会执行上面的代码,才会更
        //新parent的值,否则parent就是一个非常大的值,也就
        //是说如果一直没有遇到左子节点,那么右子节点可以非常大
        if (cur > parent)
            return false;
        //入栈
        stack.add(cur);
    }
    return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值