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

问题描述 投票:-1回答:1

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

/* 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));
    }
java recursion binary-tree binary-search-tree
1个回答
1
投票

问题是第二个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));

}

© www.soinside.com 2019 - 2024. All rights reserved.