[英]JavaScript: How to implement Binary Search Tree
我在 JavaScript 中实现二叉搜索树,但是在编写插入 function 时,发生了一些错误(很可能在 RECURSION 中)。
这是我的代码:
class BinarySearchTree {
constructor() {
this.length = 0;
this.root = null;
}
insert(elem) {
if (!this.root) {
//If root is null then this is the root.
this.root = new BSTNode(elem);
} else {
let newNode = new BSTNode(elem);
let myRoot = this.getParent(this.root, elem)
console.log(myRoot);
if (myRoot[1] == 'left') myRoot[0].left = newNode; //Error Line
else myRoot[0].right = newNode;
this.nodes.push(newNode);
this.arr.push(elem);
}
this.length++
}
getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user
if (elem < root.value) {
if (root.left!==null) this.getParent(root.left, elem);
else return [root, 'left'];
} else {
if (root.right!==null) this.getParent(root.right, elem);
else return [root, 'right']
}
}
}
class BSTNode {
constructor(val) {
this.value = val;
this.left = null; //Left Node
this.right = null; //Right Node
}
}
有两个班级; 即BinarySearchTree
和BSTNode
。
错误:
Uncaught TypeError: Cannot read property '1' of undefined
我找不到错误。
请注意,也欢迎其他解决方案来做同样的事情。
你应该返回this.getParent(root.left, elem);
的结果和this.getParent(root.right, elem);
getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user
if (elem < root.value) {
if (root.left!==null) return this.getParent(root.left, elem);
else return [root, 'left'];
} else {
if (root.right!==null) return this.getParent(root.right, elem);
else return [root, 'right']
}
}
它应该是:
getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user
if (elem < root.value) {
if (root.left!==null) return this.getParent(root.left, elem);
else return [root, 'left'];
} else {
if (root.right!==null) return this.getParent(root.right, elem);
else return [root, 'right']
}
}
在不返回这些值的情况下,它将完成查找节点的工作,但不会返回它。 大多数递归函数都返回自己,例如: function foo(){return foo()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.