Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Javascript计算二叉搜索树中目标到每个节点的距离?_Javascript_Data Structures_Binary Search Tree - Fatal编程技术网

如何使用Javascript计算二叉搜索树中目标到每个节点的距离?

如何使用Javascript计算二叉搜索树中目标到每个节点的距离?,javascript,data-structures,binary-search-tree,Javascript,Data Structures,Binary Search Tree,我刚开始学习二叉搜索树之类的东西,我试图在二叉搜索树中找到从目标到每个节点的距离。当涉及到数据结构时,很难找到javascript的示例。如果有任何帮助,我将万分感激 7 / \ 4 8 / \ / \ 3 6 / 2 for the traget of 6, my output should be {7: 2, 4:1, 3:2, 2:3, 8:3, 6:0} 到目前为止,我所拥有的: class Node {

我刚开始学习二叉搜索树之类的东西,我试图在二叉搜索树中找到从目标到每个节点的距离。当涉及到数据结构时,很难找到javascript的示例。如果有任何帮助,我将万分感激

        7
      /   \
     4     8
    / \   / \
   3   6 
  /
 2

for the traget of 6, my output should be {7: 2, 4:1, 3:2, 2:3, 8:3, 6:0}
到目前为止,我所拥有的:

class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

const calculate = (node, target) => {
  let counter = 0;
  const nodesAndThereDistances = {}

  if (!node) {
    return null;
  }
  const inner = (node, target) => {
    if (!node) {
      return null;
    }

    if (node.data !== target) {
      counter++;
      nodesAndThereDistances[node.data] = counter;
      if (node.left, target) {
        inner(node.left, target)
      }
      if (node.right, target) {
        inner(node.right, target)
      }
    } else {
      return nodesAndThereDistances;
    }
  }
  inner(node, target)
  return nodesAndThereDistances;
}

calculate(node1, 6)

你的总体目标是什么?二叉搜索树是关于缩小范围以查找值。您想找到原始列表中两个项目之间的距离,或者在算法的抽象排序过程中它们恰好落在哪里之间的距离?此外,是否存在重复项(即给定值的多个匹配项)?如果是这样,你将有多种可能性。而且,点头和距离让我发疯。“他们的”差异所以问题如下:我有多个节点。没有怀疑。每个节点仅连接到其他两个节点。计算每个节点到给定目标的距离。我刚开始学习ds,实际上我想它不一定是一个二叉搜索树,但也可以是一个二叉树(不确定在这种情况下它是否重要)。同样是的,名称不是最好的:))因此您当前的代码计算到根节点的距离,而不是到目标的距离,对吗?我试图计算到目标的距离,但先计算目标-根节点的距离。我的代码是错误的,我不知道如何真正做到这一点