The accepted answer in the following post provides all root-to-leaf paths in an n-ary tree: print all the path of n-ary tree python. How could you modify the code in the above answer (also included below) to also include paths from root to internal nodes? For example, in the tree provided in the post, the complete list would be:
[10, 2] #path from root to internal node
[10, 4] #path from root to internal node
[10, 2, 15] #path from root to leaf
[10, 2, 20] #...
[10, 2, 25]
[10, 2, 30]
[10, 4, 45]
[10, 4, 50]
[10, 4, 55]
[10, 4, 60]
How could you modify this program to complete this task?
def traverse(node, path = []):
path.append(node.data)
if len(node.child) == 0:
print(path)
path.pop()
else:
for child in node.child:
traverse(child, path)
path.pop()