print all the path of n-ary tree python

感情迁移 提交于 2020-01-24 15:35:08

问题


I want to print all the paths from the root to the leaf nodes in an N-ary tree in python. I have an idea to print it in binary tree but doing this in N-ary doesn't give me the correct result.

I'm poping and Visiting each node from the child node list here but not sure how to print the paths separately for each leaf node.

class createnode:
 def __init__(self,val):
   self.data=val
   self.child=[]

def traverse(root):
    global path
    if root.child:
     while(len(root.child)>0):
       x=root.child.pop(0)
       path.append(x.data)
       traverse(x)
    else:
      printarray(path)

def printarray(path):
  print(path)


root = createnode(10)
root.child.append(createnode(2))
root.child.append(createnode(4))

root.child[0].child.append(createnode(15))
root.child[0].child.append(createnode(20))
root.child[0].child.append(createnode(25))
root.child[0].child.append(createnode(30))

root.child[1].child.append(createnode(45))
root.child[1].child.append(createnode(50))
root.child[1].child.append(createnode(55))
root.child[1].child.append(createnode(60))
path=[]
total_val=30
traverse(root)

Expected output:

10, 2, 15

10, 2, 20

10, 2, 25

10, 2, 30

10, 4, 45

10, 4, 50

10, 4, 55

10, 4, 60


回答1:


Try this:

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()

Produces the following output with your example:

[10, 2, 15]
[10, 2, 20]
[10, 2, 25]
[10, 2, 30]
[10, 4, 45]
[10, 4, 50]
[10, 4, 55]
[10, 4, 60]



回答2:


If someone needs it in javascript:

findPaths(node, path, paths){
    let childrens = node.childrens;
    path.push(node);

    if(childrens.length == 0){
      paths.push(path.slice());

      path.pop();
    } else {
      for (let i = 0; i < children.length; i++) {
        findPaths(children, path, paths);
      }

      path.pop();
    }
}


来源:https://stackoverflow.com/questions/51911114/print-all-the-path-of-n-ary-tree-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!