[英]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.