它可能爲時已晚,但我無法入睡,直到它的解決:壓扁與父母/子女一棵樹,回報所有節點
我有一棵樹,一些家長,其中有孩子,這也紛紛兒童等
現在我需要一個函數來從樹中獲取所有節點。
這是目前的工作,但只有深入一層:
def nodes_from_tree(tree, parent):
r = []
if len(tree.get_children(parent)) == 0:
return parent
for child in tree.get_children(parent):
r.append(nodes_from_tree(tree, child))
return r
然後我試圖通過r
通過,所以它會記住那些孩子,但我使用的功能,曾多次和r
店累計的所有節點,雖然我將它設置爲r=[]
:
def nodes_from_tree(tree, parent, r=[]):
r = []
if len(tree.get_children(parent)) == 0:
return parent
for child in tree.get_children(parent):
r.append(nodes_from_tree(tree, child, r))
return r
編輯:這是樹型結構:
parent1 parent2 parent3
| | |
| | |
child | |
| |
+--------------+ |
| | | |
child child child |
| |
+---+---+ |
child child +---+---+
| |
child |
|
+-----+-----+-----+
| | | |
child child child child
可用的方法:
tree.get_parents() # returns the nodes of the very top level
tree.get_children(node) # returns the children of parent or child
樹是如何格式化即:'(價值, [(值,[...]),(的child2),..])'? – HennyH 2013-05-14 00:55:50
查看我更新的問題! – tamasgal 2013-05-14 01:01:40
什麼是回報,你期望什麼? (你可能想要回答一個小得多的例子,而不是你粘貼爲ASCII藝術的例子......) – abarnert 2013-05-14 01:03:10