【问题标题】:print all the path of n-ary tree python打印n叉树python的所有路径
【发布时间】:2018-08-18 17:33:50
【问题描述】:

我想在 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

【问题讨论】:

    标签: python data-structures graph backtracking


    【解决方案1】:

    试试这个:

    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]
    

    【讨论】:

    • 最后一组输出 [10, 2, 4, 45] 中不应有 2,因为 4 是 10 而不是 2 的子节点
    • 糟糕,我从编辑器复制粘贴时遗漏了一行。我已经更新了我的答案。
    • 欣赏您的工作。尽管我对逻辑有所了解,但您能用简单的语言表达吗? @吉姆
    • 当然。每次访问节点时,都会将其添加到当前路径。如果节点没有子节点,则打印路径。在函数返回之前,将弹出路径的最后一个条目,该条目与输入函数时添加的条目相同。 (path.pop() 实际上可以移动到 if-else 子句之后,因为两个分支都会执行我现在看到的那个操作。)
    【解决方案2】:

    如果有人在 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();
        }
    }
    

    【讨论】:

    • 基本上只是将上面的python代码转译成javascript。该函数在树结构中查找所有可能的路径。
    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多