剑指 Offer 33. 二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
思路
后序遍历是 左子树 + 右子树 + 根,左子树全小于根,右子树全大于根,dfs判断即可
待填坑:使用栈的方式判断,看了半天没看懂!!
代码
class Solution {
public boolean myVerfify(int l, int r, int[] postorder) {
if (l > r) return true;
int pos = r;
int root = postorder[r];
for (int i = l; i < r; ++i) {
if (postorder[i] > root) {
pos = i;
break;
}
}
for (int i = pos; i < r; ++i) {
if (postorder[i] < root) return false;
}
return myVerfify(l, pos-1, postorder) && myVerfify(pos, r-1, postorder);
}
public boolean verifyPostorder(int[] postorder) {
return myVerfify(0, postorder.length-1, postorder);
}
}