繁体   English   中英

查找节点与树的根部之间的距离

[英]finding the distance between a node and the root of a tree

我正在创建一种方法来查找特定节点与它所在的树的根之间的距离,并且我想验证这是否是最简单的方法。 我有点担心持有人会成为原始节点,因此,当我向上移动树时,我会将所述节点拉到我的身上。

    public int distanceToRoot(Node node)
{
    Node holder= node;
    int distance=0;
    if (node.getParent()==null)
    {
        distance=0;
    }
    else
    {
        while (holder.getParent() !=null)
            {
            holder=holder.getParent();
            distance++;
            }
    }
    return distance;
}

这是一种实现方法:

public int distanceToRoot(Node node)
{
    if (node == null) 
        /* what do you want to do in this case */;
    int d = 0;
    for(Node p=node.getParent(); p!=null; p=p.getParent()) d++;
    return d;
}

可以通过递归来完成。 从任何子节点开始,向上遍历到父节点。 找到后,返回距离。

public int distanceToRoot(Node node, int distance){
    // If no parent it must be the root, return whatever value distance currently is
    if (node.getParent()==null) return distance;

    // Otherwise, recurse passing in this node's parent and current distance plus 1
    return distanceToRoot(node.getParent(), distance + 1 );
}

初始距离应为零

int dist = distanceToRoot(aNode, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM