[英]validating a Binary Search Tree - JavaScript
我正在嘗試編寫一個驗證二進制搜索樹的函數。 我有一個可以正常工作以進行遍歷並推送到數組的版本,但是我正在嘗試也創建一個可以遞歸地跟蹤最小值和最大值的版本。 我成功地傳遞了樹,它檢查了我的第一個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));
當前代碼中有一個容易遺漏但很重要的缺陷: isValidBST()應該遞歸到自身( isValidBST() )中,而不是遞歸到忽略節點參數之后的任何參數的checkBST()中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.