I'm trying to write a function that validates a binary search tree. I got a version working where I do in order traversal and push to an array, but I'm trying to also do a version where you keep track of the min and max recursively. I am successfully passing in the tree and it checks the first node in my first checkBST function, but in the isValidBST function, the recursive calls never happen and it seems like every node is treated as null and I'm not sure why. Will appreciate anyones input!
function BinarySearchTree(value) {
this.val = value;
this.left = null;
this.right = null;
}
//insert
BinarySearchTree.prototype.insert = function (toInsert) {
if (this.val > toInsert) {
if (this.left === null) {
this.left = new BinarySearchTree(toInsert);
} else {
this.left.insert(toInsert);
}
}
if (this.val < toInsert) {
if (this.right === null) {
this.right = new BinarySearchTree(toInsert);
} else {
this.right.insert(toInsert);
}
}
};
function checkBST(node) {
// console.log(node.right);
return isValidBST(node, null, null);
}
function isValidBST(node, min, max) {
// console.log(min, max);
//this keeps getting called
if (node === null) {
console.log("CHECKING NULL");
return true;
}
// this doesn't get called, which is good
if ((min !== null && node.val > max) || (max !== null && node.val < min)) {
console.log("CHECKING NODE VALUES in false", node.val);
return false;
}
//these calls are never entered.
if (!checkBST(node.left, min, node.val) || !checkBST(node.right, node.val, max)) {
console.log("CHECKING NODE VALUES in recursive call", node.val);
return false;
}
return true;
}
var bst = new BinarySearchTree(7);
bst.insert(9);
bst.insert(6);
bst.insert(4);
console.log(checkBST(bst));