It's probably too late, but I can't sleep until it's solved:
I've got a tree with some parents, which have children, which have also children etc.
Now I need a function to get all nodes from the tree.
This is what currently works, but only with one level of depth:
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
Then I tried to pass r
through, so it remembers the children, but I'm using the function more then once and r
stores cumulatively all nodes, although I'm setting it to 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
Edit: This is the tree structure:
parent1 parent2 parent3
| | |
| | |
child | |
| |
+--------------+ |
| | | |
child child child |
| |
+---+---+ |
child child +---+---+
| |
child |
|
+-----+-----+-----+
| | | |
child child child child
Available methods:
tree.get_parents() # returns the nodes of the very top level
tree.get_children(node) # returns the children of parent or child
(value,[(value,[...]),(child2),..])
? – HennyHappend
where you meantextend
, so you end up returning a list-of-lists tree instead of a flat list. – abarnertr = [parent]
to start with, and then add onto the end of that. (And then you don't need theif
statement at all—if there are no children, you won't add anything onto the end, and will just returnparent
as-is.) – abarnert