题目:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
解答:
思路:
- 后序遍历定义: [ 左子树 | 右子树 | 根节点 ] ,即遍历顺序为 “左、右、根” 。
- 二叉搜索树定义: 左子树中所有节点的值 < 根节点的值;右子树中所有节点的值 > 根节点的值;其左、右子树也分别为二叉搜索树。
代码:
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder, 0, postorder.length - 1);
}
private boolean recur(int[] postorder, int left, int right) {
//(结束条件最后看!)左右指针重合的时候,即left~right区间只有一个数
if (left >= right) {
return true;
}
//在后序遍历中根节点一定是最后一个点
int root = postorder[right];
int index = left;
while (postorder[index] < root) {
index++;
}
int m = index;//left~right之间第一个比root大的点,即root右子树中最小的点(右子树后序遍历的起点)
//如果m~right区间(root的右子树)出现了比root小的节点,则不可能是后序遍历
while (index < right) {
if (postorder[index] < root) {
return false;
}
index++;
}
//此时能保证left ~ m-1都比root小,m ~ right-1都比root大,但这两个子区间内部的情况需要继续递归判断
return recur(postorder, left, m - 1) && recur(postorder, m, right - 1);
}
}