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

思路
- 先找到比 root 小的数列,即这个数列下一位就大于root,假设为midIndex
- midIndex之前都是比root 小的,后面从midIndex遍历到right
- 用midIndex后面的数与root比较,如果有还有小于root的说明不是后续遍历
- 如果midIndex后面的数都大于root,则从midIndex左右开始递归判断
class Solution {
private int[] postorder;
public boolean verifyPostorder(int[] postorder) {
this.postorder = postorder;
return helper(0, postorder.length - 1);
}
private boolean helper(int left, int right){
if (left >= right){
return true;
}
int midIndex = left;
int root = postorder[right];
while (postorder[midIndex] < root){
midIndex++;
}
int temp = midIndex;
while (temp < right){
if (postorder[temp] < root){
return false;
}
temp++;
}
return helper(left, midIndex - 1) && helper(midIndex, right - 1);
}
}