【问题标题】:Find the distance from any node in tree查找到树中任何节点的距离
【发布时间】:2018-09-29 10:02:59
【问题描述】:

我正在尝试从以下树中的其他节点获取节点的深度。我有一个父子关系的列表:

Parent -> Children

[2] -> [0]

[1] -> [2,5]

[5] -> [3,4,6]

我想找到一个节点与其他节点的深度/距离。 所以,从节点[5]depth[]={3,1,2,1,1,0,1}

我目前有:

def get_depth(self,idx,depth):

        self.depth[idx]=depth
        for child in self.sentence_prop.words[idx].children:
            get_depth(child[0],depth+1)
        return

其中 idx=[5] 和初始 depth=0。我只为孩子这样做,但我不知道如何为父母这样做。

【问题讨论】:

  • 这对我来说似乎不清楚。您能说明更多输入和输出示例吗? 0 的输出是什么?数字是否总是连续的 1n

标签: python-2.7 recursion tree


【解决方案1】:

我希望这能解决你的问题。

1) 2 个节点之间的距离由以下公式给出:

Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca)

这里 lca :n1 和 n2 的最低共同祖先。这适用于任何通用树。

2) 你需要做什么:

  1. 存储与您要查找距离的每个节点对应的路径 的
  2. 遍历路径以找到公共路径长度。
  3. return (len(path1)+len(path2)-2*(common_path_length))

二叉树的这个概念的实现是here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多