我正在尝试编写一个函数来验证二进制搜索树。我让一个版本按顺序遍历并推送到数组,但我也尝试做一个版本,您可以递归地跟踪min和max。我正在成功地传递树,它检查我的第一个checkBST函数中的第一个节点,但是在isValidBST函数中,递归调用永远不会发生,似乎每个节点都被视为null,我不知道为什么。将感谢任何人的投入!
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));
发布于 2015-11-17 08:56:23
当前代码中有一个很容易忽略但却很重要的缺陷: isValidBST()应该恢复到自身(isValidBST()),而不是checkBST(),后者忽略节点参数之后的任何参数。
https://stackoverflow.com/questions/33752251
复制相似问题