I\'m trying to solve this problem but I\'m having some troubles:
In a binary search tree (BST):
- The data value of every node in a
A BST is defined as:
-The left subtree of a node always contains nodes with values less than that of the node. - The right subtree of a node always contains nodes with values greater than that of the node. -Both left and right sub trees are also valid BSTs.
class Solution {
public boolean isValidBST(TreeNode root) {
return helper (root,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
public boolean helper(TreeNode root,long low,long high){
if (root==null){
return true;
}
if (root.val<low ||root.val>high){
return false;
}
return (helper(root.left,low,root.val-1) &&
helper(root.right,root.val+1,high));
}
}
Your recursion logic is not proper. I am giving here cpp logic. You may need to translate it to Java code.
bool check(Node *root) {
static Node *prev = NULL;
if(root) {
If(!check(root->left)) return false;
If(prev != Null && prev->data > root->data) return false;
Prev = root;
return check(root->right);
}
return true;
}
Something like the following should work
boolean check(Node root) {
if (root == null) {
return true;
}
if (root.left != null && max(root.left) > root.data ) {
return false
}
if (root.right != null && max(root.right) < root.data ) {
return false;
}
return check(root.left) && check(root.right);
}
Note:
max()
Your definitions are correct (although you don't necessarily need to insist that all the keys are distinct), but your code doesn't implement all the conditions in your definitions. Specifically, you don't enforce the minimum and maximum values in each subtree.
Here is an efficient recursive solution that implements your definitions:
boolean check(Node root) {
return check(root, INT_MIN, INT_MAX);
}
boolean check(Node n, int minval, int maxval) {
if (n == null) {
return true;
}
return (
n.data >= minval && n.data <= maxval &&
check(n.left, minval, n.data-1) &&
check(n.right, n.data+1, maxval)
);
}
Note that I didn't bother checking for overflow in n.data-1
and n.data+1
, which you would have to do in real life. If you want to allow duplicate keys, just change these to n.data
and you don't have to worry about it.