简体   繁体   English

查找到树中任何节点的距离

[英]Find the distance from any node in tree

I am trying to get the depth of the node from other nodes in the following tree. 我正在尝试从下面的树中的其他节点获取节点的深度。 I have a list with the parent-child relationship: 我有一个带有父子关系的列表:

Parent -> Children

[2] -> [0]

[1] -> [2,5]

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

I want to find the depth/distance of one node from other nodes. 我想找到一个节点与其他节点的深度/距离。 So, from node [5] , the depth[]={3,1,2,1,1,0,1} 因此,从节点[5]depth[]={3,1,2,1,1,0,1}

I currently have: 我目前有:

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

where idx= [5] and initial depth=0 . 其中idx = [5]和初始depth=0 I did this only for the child but I am not sure how to do it for parent. 我只是为孩子做的,但是我不确定如何为父母做。

I hope this solves your problem. 我希望这能解决您的问题。

1) The distance between 2 nodes is given by this formulae: 1)2个节点之间的距离由以下公式给出:

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

Here lca : Lowest common ancestor of n1 and n2. 此处lca:n1和n2的最低公共祖先。 This works in any general tree. 这适用于任何通用树。

2) What you need to do: 2)您需要做什么:

  1. Store paths corresponding to each node you want to find distance of 存储与您要查找距离的每个节点相对应的路径
  2. Iterate through the paths to find the common path length. 遍历路径以找到公共路径长度。
  3. return (len(path1)+len(path2)-2*(common_path_length))

The implementation of this concept for a binary tree is here 此概念在二叉树上的实现在这里

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

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