class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function isValidBST(root, min = -Infinity, max = Infinity) {
if (root === null) return true;
if (root.val <= min || root.val >= max) return false;
return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
}
// Driver code
const root = new TreeNode(5,
new TreeNode(3, new TreeNode(2), new TreeNode(4)),
new TreeNode(7, null, new TreeNode(8))
);
console.log(isValidBST(root) ? "Tree is a valid BST" : "Tree is NOT a valid BST");if (root === null) return true;
Base case: empty subtree is valid BST
if (root.val <= min || root.val >= max) return false;
Check if current node violates BST range rules
return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
Recursively check left and right subtrees with updated ranges