python - 打印n叉树python的所有路径

标签 python data-structures graph backtracking

我想在 python 中打印 N 叉树中从根到叶节点的所有路径。我有一个在二叉树中打印它的想法,但在 N 元中这样做并没有给我正确的结果。

我在此处弹出并访问子节点列表中的每个节点,但不确定如何为每个叶节点分别打印路径。

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

使用您的示例生成以下输出:

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

关于python - 打印n叉树python的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911114/

相关文章:

java - 如何计算具有给定参数的Graph中两个顶点之间的最短路径?

python - Numpy Array Division - 不支持的操作数类型/: 'list' and 'float'

python - Pandas自相关函数错误: 'DataFrame' object has no attribute 'autocorr'

Python:如何使用 Plotly 堆叠或叠加直方图

javascript - (d3) 单轴、可缩放时间轴的动态合并?

algorithm - 使用搜索和排序的不相交集

Python html 解析。我可以做准备吗?

Python名称错误,变量 'not defined'

c - 一个 C 程序,用于添加两个长度不等的单向链表,所有节点中都包含单个数字

java - 在java中实现自上而下的解析器