繁体   English   中英

实现一个任意树python

[英]implement an arbitrary tree python

似乎没有类似的话题。

我需要从整数行构建树以供将来处理。 该行包含-1到-1个节点的父级的整数。 如果其中第𝑖个节点(0≤𝑖≤𝑛− 1)为-1,则节点𝑖是根,否则它是第𝑖个节点的父节点的从0开始的索引。 例如

 the input line of integers: 4 -1 4 1 1 then -> 0 1 2 3 4 then -> 1 is the root, 3 and 4 are children of node 1, 0 and 2 are children of node 4. 

我应该能够完成剩余的工作,但是对于构造此树的处理不是很清楚。

您可以使用dict ,其中值将是代表树的子级list 这将使树的构造变得微不足道,因为对于每个节点,您只需将当前索引附加到父子节点即可。 这是使用defaultdict并将list作为默认工厂的示例:

from collections import defaultdict

s = '4 -1 4 1 1'

tree = defaultdict(list)
for node, parent in enumerate(int(x) for x in s.split()):
    tree[parent].append(node)

# Remove "parent" of the root node
root = tree.pop(-1)[0]

def print_tree(root, tree, prefix=''):
    print(prefix + str(root))
    for child in tree[root]:
        print_tree(child, tree, prefix + '  ')

print_tree(root, tree)

输出:

1
  3
  4
    0
    2

更新 :这是树遍历的另一个示例,该示例计算树中的节点数。 对于每个访问的节点,它返回1 +子节点的总和:

def count_nodes(root, tree):
    return 1 + sum(count_nodes(child, tree) for child in tree[root])

暂无
暂无

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

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