Я написал простое приложение 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
. Вы назначаете функцию-прототип addNode
для Tree
, у Node
этого нет. Любой набор
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);
}
}
}
_insert
вызывает сам себя, а также insert
. На самом деле вы не можете получить более рекурсивный подход, чем это, учитывая вставку значений.