【问题标题】:finding the distance between a node and the root of a tree查找节点与树根之间的距离
【发布时间】:2016-01-23 09:31:03
【问题描述】:

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

    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;
}

【问题讨论】:

  • 整个if-then-else 结构是不必要的。只需循环,您将获得相同的结果。
  • 甜,我只是担心让节点等价会链接内存地址,就像你用数组做的那样,然后运行循环会毁掉树

标签: java tree


【解决方案1】:

这是一种方法:

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;
}

【讨论】:

    【解决方案2】:

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

    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);
    

    【讨论】:

    • 请记住,仅仅因为递归“酷”并不意味着它是最好的工具,即使它很自然。最好的例子是计算斐波那契数。虽然 mathematical 函数是递归定义的,但对于较大的值,由于每个值的双重分支,递归实现会吞噬大量的堆栈空间——除非你添加中间结果的记忆,此时你'比简单的循环复杂一个数量级。
    • 是的。但由于它是尾递归的,因此不需要保存堆栈帧,因为不需要通过它们返回。
    • 尾递归斐波那契序列比普通递归版本更有效,因为普通递归版本需要递归直到满足基本情况,然后通过堆栈帧返回以乘以每个帧的 @ 987654323@ 值(即第一次调用斐波那契函数是实际返回解的函数)。在尾递归函数中,当满足基本情况时,无需通过任何先前的堆栈帧返回即可知道答案。 OP要求简单,所以我想到了一个递归解决方案。我不知道递归被认为是“酷”
    猜你喜欢
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2015-11-19
    • 2011-10-12
    • 1970-01-01
    • 2019-09-16
    • 2012-06-20
    • 1970-01-01
    相关资源
    最近更新 更多