【剑指OFFER】面试题33. 二叉搜索树的后序遍历序列

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

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

     5
    / \
   2   6
  / \
 1   3

示例 1:

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

示例 2:

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

提示:

数组长度 <= 1000

答案

class Solution {
    
    
    public boolean verifyPostorder(int[] postorder) {
    
    //递归判断左子树右子树是否满足条件
        if(postorder.length == 0 || postorder.length == 1) return true;
        int index = postorder.length - 1;
        for(int i = 0; i < postorder.length; i++){
    
    
            if(postorder[i] > postorder[postorder.length - 1] && index == postorder.length - 1){
    
    
                index = i;
            }
            if(i > index){
    
    
                if(postorder[i] < postorder[postorder.length - 1]) return false;
            }
        }
        int[] p1 = new int[index];
        int[] p2 = new int[postorder.length - index - 1];
        System.arraycopy(postorder, 0, p1, 0, index);
        System.arraycopy(postorder, index, p2, 0, postorder.length - index - 1);       
        return verifyPostorder(p1) && verifyPostorder(p2);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44485744/article/details/105810901