我编写了一个简单的 JavaScript p5 应用程序(使用 p5.js)来创建 BST 数据结构。使用 Firefox 运行时,它向我显示 TypeError: this.root.addNode is not a function
有人可以帮忙吗?这是完整代码(错误在第20行)
var tree;
function setup() {
noCanvas();
tree = new Tree();
tree.addValue(5);
tree.addValue(3);
console.log(tree);
}
function Tree() {
this.root = null;
}
Tree.prototype.addValue = function (val) {
var n = new Node(val);
if (this.root == null) {
this.root = n;
} else {
this.root.addNode(n);
}
}
Tree.prototype.addNode = function (n) {
if (n.value < this.value)
if (this.left == null) {
this.left = n;
} else {
this.left.addNode(n);
}
} else if (n.value > this.value) {
if (this.right == null) {
this.right = n;
} else {
this.right.addNode(n);
}
}
}
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
最佳答案
root
只是您稍后指定为 Node
的属性。您将原型(prototype)函数 addNode
分配给 Tree
,Node
没有。要么设置
this.root = new Tree();
或者将原型(prototype)方法 addNode
分配给 Node
。
关于javascript - 类型错误 : 'addNode' is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50787165/