类型错误:“addNode”不是函数

问题描述 投票:0回答:3

我编写了一个简单的 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;
}
javascript p5.js
3个回答
1
投票

root
只是您稍后指定为
Node
的属性。您将原型函数
addNode
分配给
Tree
Node
没有。要么设置

this.root = new Tree();

或者将原型方法

addNode
分配给
Node


0
投票

如果您有兴趣,这就是您可以使用

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);
    }
  }
}

0
投票
var tree;

function setup() {
  noCanvas();
  tree = new Tree();
  tree.addValue(5);
  tree.addValue(3);

  console.log(tree);
}

const Tree = function () {
  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);
  }
};

const Node = function (val) {
  this.value = val;
  this.right = null;
  this.left = null;
};

Node.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);
    }
  }
};

console.log("end!");
© www.soinside.com 2019 - 2024. All rights reserved.