打印n元树python的所有路径 [英] print all the path of n-ary tree python

查看:89
本文介绍了打印n元树python的所有路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python的N元树中打印从根到叶节点的所有路径.我有一个想法可以在二叉树中打印出来,但是在N-ary中这样做并不能给我正确的结果.

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)

预期输出:

10,2,15

10,2,20

10,2,25

10,2,30

10、4、45

10、4、50

10,4,55

10,4,60

推荐答案

尝试一下:

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]

这篇关于打印n元树python的所有路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆