简体   繁体   English

实现一个任意树python

[英]implement an arbitrary tree python

It seems no similar topic exists. 似乎没有类似的话题。

I am required to build a tree from a line of integers for future processing. 我需要从整数行构建树以供将来处理。 This line contains 𝑛 integer numbers from −1 to 𝑛 − 1 — parents of nodes. 该行包含-1到-1个节点的父级的整数。 If the 𝑖-th one of them (0 ≤ 𝑖 ≤ 𝑛 − 1) is −1, node 𝑖 is the root, otherwise it's 0-based index of the parent of 𝑖-th node. 如果其中第𝑖个节点(0≤𝑖≤𝑛− 1)为-1,则节点𝑖是根,否则它是第𝑖个节点的父节点的从0开始的索引。 eg 例如

 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. 

I should be able to do the remaining job but not very clear about the processing of constructing this tree. 我应该能够完成剩余的工作,但是对于构造此树的处理不是很清楚。

You could use dict where values would be list of children to represent the tree. 您可以使用dict ,其中值将是代表树的子级list This would make construction of the tree trivial since for every node you can just append the current index to parent children. 这将使树的构造变得微不足道,因为对于每个节点,您只需将当前索引附加到父子节点即可。 Here's an example using defaultdict with list as default factory: 这是使用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)

Output: 输出:

1
  3
  4
    0
    2

Update : Here's an additional example of tree traversal which counts the number of nodes in the tree. 更新 :这是树遍历的另一个示例,该示例计算树中的节点数。 For every node visited it returns 1 + sum of child nodes: 对于每个访问的节点,它返回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