0
/ \
1 2
/ \ /|\
3 4 5 6 7
I'm trying to return the nodes without children (3,4,5,6,7) from an object using a recursive function.
It works using a global variable and this function:
def find(self, nodes):
if not hasattr(self, 'children'):
nodes.append(self)
else:
for i in self.children:
i.find(nodes)
nodes = []
node.find(nodes) # can be any node (0,1,2,3,4, etc.)
print(nodes)
But I would like to use return in my function. I tried something like this:
def find2(self):
if not hasattr(self, 'children'):
return self
else:
for i in self.children:
return i.find2()
nodes = root.find2()
print(nodes)
But I get only 1 node. I also tried passing an array like on this post: PYTHON Return a list from a recursive function. But I don't get the result I want because tree structure (I guess)...
I'm stuck, can you help me? How to "return the result for each iteration of the recursive function to a variable"? Thank you