Javascript 给定一个二叉搜索树和两个节点n1和n2,编写一个函数来查找两个节点之间的距离

Javascript 给定一个二叉搜索树和两个节点n1和n2,编写一个函数来查找两个节点之间的距离,javascript,binary-search-tree,Javascript,Binary Search Tree,给定一个二叉搜索树,我需要编写一个函数来查找两个节点之间的距离。我想我和这个很接近,但它似乎不能正常工作。如果要搜索树同一侧的节点之间的距离。我不知道如何解决这个问题。任何提示都将不胜感激。下面是我到目前为止的代码。我的代码是用Javascript编写的 function Node(val){ this.value = val; this.left = null; this.right = null; } function BinarySearchTree(value) { t

给定一个二叉搜索树,我需要编写一个函数来查找两个节点之间的距离。我想我和这个很接近,但它似乎不能正常工作。如果要搜索树同一侧的节点之间的距离。我不知道如何解决这个问题。任何提示都将不胜感激。下面是我到目前为止的代码。我的代码是用Javascript编写的

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

function BinarySearchTree(value) { 
 this.root = null;
};

BinarySearchTree.prototype.push = function(val){
   var root = this.root;

   if(!root){
      this.root = new Node(val);
      return;
   }

   var currentNode = root;
   var newNode = new Node(val); 

   while(currentNode){
      if(val < currentNode.value){
          if(!currentNode.left){
             currentNode.left = newNode;
             break;
          }
          else{
             currentNode = currentNode.left;
        }
     }
     else{
         if(!currentNode.right){
            currentNode.right = newNode;
            break;
         }
         else{
            currentNode = currentNode.right;
         }
     }
  }

}

BinarySearchTree.prototype.levelOfNode = 
    function(root, key, level){
      if(root === null){
        return -1;
      }else if(root.value === key){
        return level;
      }
  let l = this.levelOfNode(root.left, key, level+1)
    if (l!== -1){
      return l;
    }
    return this.levelOfNode(root.right, key, level +1)
  }

BinarySearchTree.prototype.lca = function(root, n1, n2){
   if(!root) return;
   var val = root.value;
   if(n1<val && n2<val){
     return lca(root.left, n1, n2);
   }
   if(n1>val && n2>val){
     return lca(root.right, n1, n2);
  }
  return this.root;
}

BinarySearchTree.prototype.findDistance = function(root, n1, n2){
  let lcaValue = this.lca(root, n1, n2);

  let l1 = this.levelOfNode(lcaValue, n1, 0);
  let l2 = this.levelOfNode(lcaValue, n2, 0);

  return l1 + l2;

}

let tree = new BinarySearchTree();

tree.push(4);
tree.push(8);
tree.push(9);
tree.push(11);
tree.push(3);

tree.findDistance(4,8,11);
功能节点(val){
this.value=val;
this.left=null;
this.right=null;
}
函数二进制搜索树(值){
this.root=null;
};
BinarySearchTree.prototype.push=函数(val){
var root=this.root;
如果(!root){
this.root=新节点(val);
返回;
}
var currentNode=root;
var newNode=新节点(val);
while(当前节点){
if(val
当你有一棵看起来像

您可以从根获取每个目标的路径,并

消除所有公共节点。然后检查一个路径数组是否为空,并取另一个路径数组的长度

如果有两个非空数组,可以将两个数组的长度相加,如

删除公共节点后

然后将两个长度相加

   4
3     8
         9
           11
[4, 8]
[4, 8, 9, 11]
[4, 3]
[4, 8, 9]
[3]
[8, 9]
1 + 2 = 3