我编写了一个简单的JavaScript p5应用程序(使用p5.js)来创建BST数据结构。当我在火狐上运行它时,它显示了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;
}
发布于 2018-06-11 03:16:45
root
只是一个稍后指定为Node
的属性。你将原型函数addNode
赋值给Tree
,Node
没有这个。任一组
this.root = new Tree();
或者改为将原型方法addNode
分配给Node
。
发布于 2018-06-11 03:34:21
如果你感兴趣,这就是你可以使用class
关键字实现它的方式,它为你处理了很多手动的原型处理,所以它不太容易出错。
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
class Tree {
constructor() {
this.root = null;
}
_insert(target, key) {
if (target.key > key) {
if (!target.left) {
target.left = new Node(key);
} else {
this._insert(target.left, key);
}
} else {
if (!target.right) {
target.right = new Node(key);
} else {
this._insert(target.right, key);
}
}
}
insert(key) {
if (!this.root) {
this.root = new Node(key);
} else {
this._insert(this.root, key);
}
}
}
https://stackoverflow.com/questions/50787165
复制相似问题