题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例
输入: [1,6,3,2,5]
输出: false
输入: [1,3,2,6,5]
输出: true
代码
- 后序遍历:
[左子树 | 右子树 | 根节点]
- 二叉搜索树:左子树的所有节点值 < 根节点值;右子树的所有节点值 > 根节点值
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder, 0, postorder.length - 1);
}
private boolean recur(int[] postorder, int i , int j) {
//i >= j,说明此子树节点数量<=1,直接返回true
if (i >= j) {
return true;
}
//左子树的所有节点值都应该小于根节点值
int p = i;
while (postorder[p] < postorder[j]) p++;
//找到第一个大于根节点值的节点,这个节点是右子树的根节点
int m = p;
//右子树的所有节点值都应该大于根节点值
while (postorder[p] > postorder[j]) p++;
//左子树[i, m-1], 右子树[m, j-1]
return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof