所以我嘗試使用僞古典繼承創建二叉搜索樹。它接受一個數組,對它進行排序,使用中間值作爲起點,並將數組中剩餘的值插入到BST中。我想我正在盡我所能利用函數式編程(糾正我,如果我錯了請)通過使用可重用的方法,也因爲BST插入方法需要遞歸。嘗試使用僞古典繼承創建BST時遞歸函數的問題
我已經指出了代碼出錯的地方。我相信它需要3作爲初始值,我也相信1(數組中的下一個值)成功插入,但我相信數字2是錯誤發生的地方,當它說「TypeError:this.left.insert是不是功能「。任何人都可以指出我做錯了什麼?爲什麼插入方法不會爲this.left調用它自己?
var NoDuplicatesBST = function(array) {
var tempArr = arguments[0].sort(function(a, b) {
return a-b;
});
var middle = Math.floor(((tempArr.length - 1)/2));
var sliced = tempArr.splice(middle, 1);
this.createBST(sliced[0]);
// now insert the rest of tempArr into the BST
for (var i = 0; i < tempArr.length; i++) {
this.insert(tempArr[i]);
}
};
NoDuplicatesBST.prototype.createBST = function(number) {
this.value = number;
this.left = null;
this.right = null;
};
NoDuplicatesBST.prototype.insert = function(number) {
if (number < this.value) {
if (this.left === null) {
this.left = new this.createBST(number);
} else {
// ------------CODE BELOW DOES NOT WORK!, LINED 77 ALSO PROBABLY. TypeError: this.left.insert is not a function----------------------
this.left.insert(number);
}
} else if (number > this.value) {
if (this.right === null) {
this.right = new this.createBST(number);
} else {
this.right.insert(number);
}
} else {
// Do nothing
}
};
var testBST = new NoDuplicatesBST([2,3,4,5,1]);
console.log("The testBST:", testBST);
你使用'this.createBST(number)'作爲構造函數,這不是一個構造函數,爲你的節點創建一個單獨的類 – Oskar