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

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

递归分治

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        return verifyPostorder(postorder, 0, postorder.length - 1);
    }

    boolean verifyPostorder(int[] postorder, int l, int r){
        if(l >= r) return true;
        int root = postorder[r];

        int i = l;
        while(i < r && postorder[i] < root) i++;

        int j = i;
        while(j < r && postorder[j] > root) j++;
        if(j < r) return false;

        return verifyPostorder(postorder, l, i - 1) && verifyPostorder(postorder, i, r - 1);
    }
}

单调栈

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        Deque<Integer> stack = new ArrayDeque<>();
        int root = Integer.MAX_VALUE;
        for(int i = postorder.length - 1; i >= 0; i--){
            if(postorder[i] > root) return false;
            while(!stack.isEmpty() && stack.peek() > postorder[i]) root = stack.pop();
            stack.push(postorder[i]);
        }
        return true;
    }
}

你可能感兴趣的:(#,剑指offer,算法)