JavaScript:如何实现二进制搜索树

JavaScript:如何实现二进制搜索树,javascript,data-structures,Javascript,Data Structures,我正在用JavaScript实现二进制搜索树,但在编写insert函数时,出现了一些错误(很可能是在递归中) 这是我的密码: 类二进制搜索树{ 构造函数(){ 这个长度=0; this.root=null; } 插入(元素){ 如果(!this.root){ //如果root为null,则这是根。 this.root=新节点(elem); }否则{ 设newNode=newbstnode(elem); 让myRoot=this.getParent(this.root,elem) console.

我正在用JavaScript实现二进制搜索树,但在编写insert函数时,出现了一些错误(很可能是在递归中)

这是我的密码:

类二进制搜索树{
构造函数(){
这个长度=0;
this.root=null;
}
插入(元素){
如果(!this.root){
//如果root为null,则这是根。
this.root=新节点(elem);
}否则{
设newNode=newbstnode(elem);
让myRoot=this.getParent(this.root,elem)
console.log(myRoot);
如果(myRoot[1]=='left')myRoot[0]。left=newNode;//错误行
else myRoot[0]。right=newNode;
this.nodes.push(newNode);
本协议推送(elem);
}
这个长度++
}
getParent(root,elem){//参数'root'不明确,但它是针对用户的
if(元素<根值){
if(root.left!==null)this.getParent(root.left,elem);
else返回[根,'左'];
}否则{
if(root.right!==null)this.getParent(root.right,elem);
else返回[root,‘right']
}
}
}
类节点{
构造函数(val){
this.value=val;
this.left=null;//左节点
this.right=null;//右节点
}
}
有两个班;即
BinarySearchTree
BSTNode

错误:
未捕获类型错误:无法读取未定义的属性“1”

我找不到错误


请注意,也欢迎使用其他解决方案来做同样的事情。

您应该返回this.getParent(root.left,elem)的
结果
this.getParent(root.right,elem)

getParent(root,elem){//参数'root'不明确,但它是针对用户的
if(元素<根值){
if(root.left!==null)返回此.getParent(root.left,elem);
else返回[根,'左'];
}否则{
if(root.right!==null)返回此.getParent(root.right,elem);
else返回[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']
    }
  }
getParent(root,elem){//参数'root'不明确,但它是针对用户的
if(元素<根值){
if(root.left!==null)返回此.getParent(root.left,elem);
else返回[根,'左'];
}否则{
if(root.right!==null)返回此.getParent(root.right,elem);
else返回[root,‘right']
}
}

在不返回这些值的情况下,它将完成查找节点的工作,但不会返回该节点。大多数recurive函数都返回它们自己,比如:
function foo(){return foo()}

您好,欢迎来到StackOverflow,它说myRoot还没有定义!您确定myRoot定义正确吗?
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']
    }
  }