I'm trying to adapt this answer in two ways:
- I want to make the traverse function a class method, and
- I want a call to traverse to yield the list of all root-to-leaf paths (list of lists) in the tree
First change was trivial, second one I'm struggling with. Here's my class definition:
class createnode:
""" thanks to https://stackoverflow.com/a/51911296/1870832"""
def __init__(self,nodeid):
self.nodeid=nodeid
self.child=[]
def __str__(self):
print(f"{self.nodeid}")
def traverse(self, path = []):
path.append(self.nodeid)
if len(self.child) == 0:
#print(path)
yield path
path.pop()
else:
for child in self.child:
child.traverse(path)
path.pop()
I construct a tree with:
ROOT_NODE = 0
root = createnode(ROOT_NODE)
lvl1 = [createnode(1), createnode(2), createnode(3)]
root.child += lvl1
root.child[0].child += [createnode(4), createnode(5)]
root.child[1].child += [createnode(6), createnode(7)]
root.child[2].child += [createnode(8), createnode(9)]
Desired output for printing all full root-leaf paths (e.g. w/ code below)
paths = root.traverse()
for p in paths:
print(p)
is:
[0, 1, 4]
[0, 1, 5]
[0, 2, 6]
[0, 2, 7]
[0, 3, 8]
[0, 3, 9]