无法找到下面的代码有什么问题,请让我知道问题是什么...我正在尝试构造二叉搜索树,但无法构造。
function BinarySearchTree(){
var Node = function(key){
this.key = key;
this.left = null;
this.right = null;
};
var root = null;
}
//Inserting a Key into a tree
this.insert = function(key){
var newNode = new Node(key);
if(root === null){
root = newNode;
}else{
insertNode(root, newNode);
}
};
var insertNode = function(node, newNode){
if(newNode.key < node.key){
if(node.left === null){
node.left = newNode;
}else{
insertNode(node.left, newNode);
}
}else{
if(node.right === null){
node.right = newNode;
}else{
insertNode(node.right, newNode);
}
}
};
var tree = BinarySearchTree();
tree.insert(11);
最佳答案
评论者提到了代码中的一些问题,这些问题导致了挂起。首先,您在 constructor
或 prototype
函数之外使用 this
,因此 this
将被评估为引用全局对象。另外,当您将 BinarySearchTree
分配给变量 tree
时,您并没有调用构造函数,因此如果您要 console.log(tree)
,它将返回值未定义
。
那么如何解决您的问题?
首先,您可以在 BinarySearchTree
(以下简称 BST)定义中添加一个检查,以返回对象的实例,以防您忘记 new
关键字。
if (!(this instanceof BinarySearchTree)) {
return new BinarySearchTree();
}
其次,您希望将 Node
构造函数和 root
变量绑定(bind)到 BST 对象,方法是将 var
替换为 this。节点
和this.root
。现在您可以稍后在您将定义的各种 prototype
函数中访问它们。
第三,如上所述,重构 insert
函数的定义,如下所示:
BinarySearchTree.prototype.insert = function(){}
当然,用适当的代码填充函数。对 insertNode
执行相同操作。
BinarySearchTree.prototype.insertNode = function(){}
我并不是说代码可以工作,但这应该创建您的树作为对象运行所需的原型(prototype)继承。
重构
function BinarySearchTree(){
if (!(this instanceof BinarySearchTree)) {
return new BinarySearchTree();
}
this.Node = function(key){
this.key = key;
this.left = null;
this.right = null;
};
this.root = null;
}
//Inserting a Key into a tree
BinarySearchTree.prototype.insert = function(key){
var newNode = new this.Node(key);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
}
};
BinarySearchTree.prototype.insertNode = function(node, newNode){
if(newNode.key < node.key){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
}
}else{
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right, newNode);
}
}
};
var tree = BinarySearchTree();
tree.insert(11);
关于javascript - 未捕获的类型错误 : Cannot read property 'insert' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51247593/