Check Whether a Tree Is a Valid BST
Check Whether a Tree Is a Valid BST
Complete the private helper isValid(Node node, Integer min, Integer max) so BSTValidator.isValid(root) returns true only when the whole tree follows the BST rule.
Reminder: the BST rule covers whole subtrees, not just children. In a binary search tree every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger, all the way down. Comparing each parent with its own two children is not enough:
50
/ \
30 70
\
60Here 60 is a fine right child of 30, but it sits in the left subtree of 50, where every value must be smaller than 50, so this is not a BST. The provided checksOnlyChildren(Node node) makes exactly that mistake and calls this tree valid.
The fix is to pass limits down as you recurse. Every node must fit strictly between a lower limit min and an upper limit max. Going left, the current value becomes the new max; going right, it becomes the new min. A null limit means that side has no limit yet, which is how the root starts.
Requirements:
1. An empty subtree (node is null) is valid.
2. Return false when min is not null and node.value <= min, or when max is not null and node.value >= max. A BST here never holds the same value twice.
3. Otherwise the tree is valid only when the left subtree is valid with max = node.value and the right subtree is valid with min = node.value.
4. Do not change checksOnlyChildren or the public isValid(Node root). The tests print checksOnlyChildren next to your answer so you can see where the shortcut goes wrong.
The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.
Do NOT write a main method.
Expected Output:
true true true false
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...