Javascript 类型错误:';addNode';这不是一个函数
我编写了一个简单的JavaScript p5应用程序(使用p5.js)来创建BST数据结构。在Firefox上运行时,它向我显示Javascript 类型错误:';addNode';这不是一个函数,javascript,p5.js,Javascript,P5.js,我编写了一个简单的JavaScript p5应用程序(使用p5.js)来创建BST数据结构。在Firefox上运行时,它向我显示TypeError:this.root.addNode不是一个函数 有人能帮忙吗?这是完整代码(错误在第20行) var树; 函数设置(){ noCanvas(); tree=新树(); 附加值(5); 附加值(3); 控制台日志(树); } 函数树(){ this.root=null; } Tree.prototype.addValue=函数(val){ var n=
TypeError:this.root.addNode不是一个函数
有人能帮忙吗?这是完整代码(错误在第20行)
var树;
函数设置(){
noCanvas();
tree=新树();
附加值(5);
附加值(3);
控制台日志(树);
}
函数树(){
this.root=null;
}
Tree.prototype.addValue=函数(val){
var n=新节点(val);
if(this.root==null){
this.root=n;
}否则{
this.root.addNode(n);
}
}
Tree.prototype.addNode=函数(n){
如果(n.值<此.值)
if(this.left==null){
这个左=n;
}否则{
this.left.addNode(n);
}
}else if(n.value>this.value){
if(this.right==null){
这个。右=n;
}否则{
this.right.addNode(n);
}
}
}
功能节点(val){
this.value=val;
this.left=null;
this.right=null;
}
根
只是一个属性,稍后您可以将其指定为节点
。将原型函数addNode
分配给树
,节点
没有该函数。任何一套
this.root = new Tree();
或者将原型方法
addNode
分配给Node
如果您感兴趣,可以使用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);
}
}
}
我想我可以使用类,但我尝试递归地使用。无论如何,我会试试的。谢谢man@Alexi上面的代码是递归的,
\u insert
调用自身以及insert
。考虑到值插入,实际上没有比这更递归的了。
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);
}
}
}