我需要计算树中两个节点之间的距离。 我实施了通用公式:
stack<std::string>().swap(pages);
代码适用于大多数输入,但如果我尝试(父亲,儿子)我得到了错误的距离。 这是我的代码:
Dist(n1,n2) = Dist(root,n1), Dist(root,n2) - 2*Dist(root,lca)
对于简单的树:
public static int distance(Tree t, Node<String> node1, Node<String> node2)
{
Node<String> lca = lca(node1, node2);
//This if statement is when the input contains the root itself
//this means that the distance is simply from the node and the root
if(lca==null)
{
// the function getNumberOfAncestors returns exactly the distance between a generic node and the root, since I count parent by parent and so on.
return node1.getNumberOfAncestors() + node2.getNumberOfAncestors();
}
return node1.getNumberOfAncestors() + node2.getNumberOfAncestors() - 2*distance(t, t.getRoot(), lca);
}
我们知道Dist(C,G)= 1,但我的算法返回3。 有什么想法吗?
答案 0 :(得分:0)
请提供方法lca的实现,以便我们检查它是否以正确的方式工作。我非常确定distance
会返回3,因为lca(node1, node2)
为空。在这种情况下
lca == null
为真,方法返回
node1.getNumberOfAncestors() + node2.getNumberOfAncestors()
基本上是
node1.getNumberOfAncestors() = 1
代表C +
node2.getNumberOfAncestors() = 2