【Leetcode】剑指offer33.二叉搜索树的后序遍历序列 题解

题目

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

参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:

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

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

提示:

数组长度 <= 1000

题目链接

思路

记录一下二叉搜索树的性质:
左子树节点值小于根节点,右子树节点值大于根节点。
每次递归找到第一个大于根节点的位置,验证之后的节点值是否都大于根节点。
注意递归的终止条件是返回true,而不是返回false.

代码

class Solution {
    /**
     * 后序遍历是左右根
     * 二叉搜索树是左子树小于根节点,右子树大于根节点
     */
    public boolean verifyPostorder(int[] postorder) {
        if(postorder == null || postorder.length == 0)
            return true;
        return judge(postorder, 0, postorder.length - 1);
    }

    //闭区间
    private boolean judge(int[] postorder, int start, int end) {
        if(end <= start) {
            //终止条件 走到底了
            return true;
        }
        //找到最后一个小于根节点的值,即为根节点
        int i = start;
        while (i < end) {
            if(postorder[i] < postorder[end])
                i ++;
            else
                break;
        }
        //检查右子树中有没有小于根节点的值
        for (int j = i; j < end; j++) {
            if(postorder[j] < postorder[end]) return false;
        }
        return judge(postorder, start, i - 1) && judge(postorder, i, end - 1);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41279172/article/details/108504491