检查二叉搜索树是否有效 [HackerRank]

Checking if Binary Search Tree is valid [HackerRank]

我正在尝试检查 BST 是否有效。以下是我的代码。来自 HackerRank 的输入 1 2 3 4 5 6 7 我的代码总是返回 False 即使 BST 有效。

/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.  

The Node class is defined as follows:
    class Node {
    int data;
    Node left;
    Node right;
     }
*/
    boolean checkBST(Node root) {
        return isValidBSTHelper(root, root.data);

    }

    private boolean isValidBSTHelper(Node root, int limit) {

        if (root == null) return true;
        if (root.left != null) {
           if (root.left.data > root.data || root.left.data > limit) return false;
        }
        if (root.right != null) {
           if (root.right.data < root.data || root.right.data < limit) return false;
        }
        return (isValidBSTHelper(root.left, root.data) &&  isValidBSTHelper(root.right, root.data));
    }

问题出在第二个 if 语句上。以下解决问题。

/* The Node class is defined as follows:

        class Node {
        int data;
        Node left;
        Node right;
         }
    */
        boolean checkBST(Node root) {
            return isValidBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);

        }

        private boolean isValidBSTHelper(Node root, int min, int max) {

            if (root == null) return true;
            if (root.data > max || root.data < min) return false;
            return (isValidBSTHelper(root.left, min, root.data) &&  isValidBSTHelper(root.right, root.data, max));

}

HackerRank 在这是二叉搜索树吗?

需要 -> 检查条件为:

if (root.data >= max || root.data <= min) return false;