首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印n元树python的所有路径

打印n元树python的所有路径
EN

Stack Overflow用户
提问于 2018-08-19 01:33:50
回答 2查看 3.2K关注 0票数 2

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

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

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-19 01:59:03

试试这个:

代码语言:javascript
复制
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()

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

代码语言:javascript
复制
[10, 2, 15]
[10, 2, 20]
[10, 2, 25]
[10, 2, 30]
[10, 4, 45]
[10, 4, 50]
[10, 4, 55]
[10, 4, 60]
票数 4
EN

Stack Overflow用户

发布于 2019-05-17 23:08:16

如果有人在javascript中需要它:

代码语言: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();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51911114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档