剑指 Offer 33. 二叉搜索树的后序遍历序列

剑指 Offer 33. 二叉搜索树的后序遍历序列

Difficulty: 中等

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

     5
    / 
   2   6
  / 
 1   3

示例 1:

输入: [1,6,3,2,5]
输出: false

示例 2:

输入: [1,3,2,6,5]
输出: true

提示:

  1. 数组长度 <= 1000

Solution

思路:判断根结点的左右子树是否满足二叉搜索树的特性,然后递归的判断左右子树是否同样满足。

Language: java

​class Solution {
    public boolean verifyPostorder(int[] postorder) {
        return helper(postorder, 0, postorder.length-1);
    }
    private boolean helper(int[] postorder, int s, int e){
        if(s >= e) return true;
        int i = s;
        while(i < e && postorder[i] < postorder[e]) i++;
        int ii = e;
        while(ii > i && postorder[ii-1] >= postorder[e]) ii--;
        if(i != ii) return false;  //左子树不满足比根结点小,或右子树不满足比根结点小
        return helper(postorder, s, i-1) && helper(postorder, i, e-1);
    }
}
原文地址:https://www.cnblogs.com/liuyongyu/p/14452181.html