问题描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
问题解决
对于解决树相关问题,很多时候使用递归的方法。
class Solution {
public boolean verifyPostorder(int[] postorder) {
if(postorder == null || postorder.length == 0) return true;
return recur(postorder, 0, postorder.length - 1);
}
public boolean recur(int[] postorder, int left, int rootIndex) {
if(left >= rootIndex) return true;
int right = rootIndex - 1, start = left, end = right;
while(right >= 0 && postorder[right] > postorder[rootIndex]) {
right--;
}
while(left < rootIndex && postorder[left] < postorder[rootIndex]) {
left++;
}
if(left - right != 1) return false;
return recur(postorder, start, right) && recur(postorder, left, end);
}
}
327

被折叠的 条评论
为什么被折叠?



