首先明确后序遍历结果的特点
同样的对于每个子树,也应该满足上面的情况
所以我们只需要利用递归分治的思想,判断每个子树区间是否满足条件即可
代码如下:
class Solution {
int[] seq;
public boolean verifyPostorder(int[] postorder) {
seq = postorder;
if (postorder.length == 0) return true;
return helper(0, seq.length - 1);
}
private boolean helper(int start, int end) {
if (start > end) return true;
int root = seq[end];
int p = start;
while (p < end && seq[p] < root) p++;
int m = p;
while (p < end && seq[p] > root) p++;
return p == end && helper(start, m - 1) && helper(m, end-1);
}
}