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

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

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

     5
    / \
   2   6
  / \
 1   3

示例 1:

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

示例 2:

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

提示:

  1. 数组长度 <= 1000
class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder == null || postorder.length == 0) return true;
        return verify(postorder,0,postorder.length - 1);     
    }
    private boolean verify(int[] post,int l,int h){
        if(l >= h) return true;
        int rootVal = post[h];
        int i = l;
        while(post[i] < rootVal){
            i++;
        }
        for(int j = i + 1;j < h;j++){
            if(post[j] < rootVal) return false;
        }
        return verify(post,l,i - 1) && verify(post,i,h - 1);
    }
}

猜你喜欢

转载自www.cnblogs.com/zzytxl/p/12629987.html