确定 BST 树中节点对之间的距离

时间:2021-06-05 17:54:43

标签: data-structures tree binary-search-tree nodes pseudocode

我想编写一个伪代码来查找 BST 中 2 个节点之间的距离。

我已经实现了 LCA 功能。

这是我的尝试:

findDistance(root,p,q){
  if(root==null) return -1;
  Node LCA = findLCA(root,p,q);
  d1=distance(p,LCA);
  d2=distance(q,LCA);
  return abs(d1-d2);
}

我唯一的问题是我不知道如何计算节点与其 LCA 之间的距离。

任何帮助都会很棒!

谢谢!

1 个答案:

答案 0 :(得分:1)

找到 LCA 很有帮助,但您可以同时确定 LCA。

我将首先定义一个辅助函数,它将给出从根到给定节点的路径。由于根是唯一没有父节点的节点,因此我们实际上不需要为此函数提供根:

function getPath(p) {
    let path = [];
    // Walk up the tree and log each node
    for (let node = p; node != null; node = node.parent) {
        path.push(node);
    }
    // We want the root to be first element of path, and p to be the last:
    return path.reverse(); 
}

现在有了这个函数,我们可以收集两个给定节点的两条路径。那么我们可以忽略这两条路径中的公共前缀(最后一个公共节点是LCA)。路径的剩余长度应该求和以获得最终结果:

function findDistance(p, q) {
    let path1 = getPath(p);
    let path2 = getPath(q);
    let len = min(path1.length, path2.length);
    // Find the index where the paths diverge
    let i = 0;
    while (i < len && path1[i] == path2[i]) {
        i++;
    }
    // LCA is at path1[i-1] == path2[i-1]
    // Subtract the nodes that the paths have in common (from both):
    return path1.length + path2.length - i*2;
}
相关问题