剑指offer33 判断指定序列是否是二叉搜索树的后序遍历 Java

public class VerifySequenOfBST33_ {

    public static void main(String[] args) {
        int[] arr = {5, 7, 6, 9, 11, 10, 8};
        System.out.println(check(arr, 0, arr.length - 1));
    }

    private static boolean check(int[] arr, int start, int end) {
        if (end - start <= 1) {
            //只有两个节点 或者一个节点 一定可以构成二叉搜索树
            return true;
        }
        int root = arr[end];
        int index = start;
        for (; index < end; index++) {
            if (arr[index] > root)
                break;
        }
        for (int i = index; i < end; i++) {
            if (arr[index] < root)
                return false;
        }
        return check(arr, start, index - 1) && check(arr, index, end - 1);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43065507/article/details/99337789