剑指offer_23:二叉搜索树的后序遍历序列

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

参考以下这颗二叉搜索树:

示例 1:
输入: [1,6,3,2,5]
输出: false

示例 2:
输入: [1,3,2,6,5]
输出: true

提示:
数组长度 <= 1000

1、递归

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder.length==0) return true;
        return verifyPostorder(postorder,0,postorder.length-1);
    }
    public boolean verifyPostorder(int[] postorder,int start,int end){
        if(start>=end) return true;
        int index=start;
        for(int i=start;i<end;i++){
            if(postorder[i]<postorder[end]){
                index++;
            }else{
                break;
            }
        }
        for(int i=index+1;i<end;i++){
            if(postorder[i]<postorder[end]){
                return false;
            }
        }
        return verifyPostorder(postorder,start,index-1)&&
            verifyPostorder(postorder,index,end-1);
    }
}

2、非递归

可以用栈

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        Stack<Integer> stack=new Stack<>();
        int parent=Integer.MAX_VALUE;
        for(int i=postorder.length-1;i>=0;i--){
            int cur=postorder[i];
            while(!stack.isEmpty()&&cur<stack.peek()){
                parent=stack.pop();
            }
            if(cur>parent){
                return false;
            }
            stack.push(cur);
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/xyz-1024/p/14243257.html