树算法问题中两个节点之间的距离

时间:2016-10-23 10:08:56

标签: java algorithm tree nodes

我需要计算树中两个节点之间的距离。 我实施了通用公式:

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。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

请提供方法lca的实现,以便我们检查它是否以正确的方式工作。我非常确定distance会返回3,因为lca(node1, node2)为空。在这种情况下 lca == null为真,方法返回

node1.getNumberOfAncestors() + node2.getNumberOfAncestors()

基本上是

node1.getNumberOfAncestors() = 1代表C +

对于G = 3

node2.getNumberOfAncestors() = 2

相关问题