我正在尝试检查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));
}
答案 0 :(得分: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));
}
答案 1 :(得分:0)
这是二叉搜索树中的HackerRank吗?
需要->将条件检查为:
if (root.data >= max || root.data <= min) return false;