我正在尝试从下面的树中的其他节点获取节点的深度。我有一个带有父子关系的列表:
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 :(得分:0)
我希望这可以解决您的问题。
1)2个节点之间的距离由以下公式给出:
Dist(n1,n2)= Dist(root,n1)+ Dist(root,n2)-2 * Dist(root, lca)
此处lca:n1和n2的最低共同祖先。这可以在任何普通树中使用。
2)您需要做什么:
return (len(path1)+len(path2)-2*(common_path_length))
针对二叉树的此概念的实现为here