剑指 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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
单调栈
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;
}
}