如何在列表中存储树的所有dfs路径?

时间:2019-07-09 08:38:10

标签: python-3.x tree depth-first-search tree-traversal

def traverse(node, path =[]):
    path.append(node.val)
    if len(node.children)==0:
       print(path)
       path.pop()
   else:
       for child in node.children:
           traverse(child)    
       path.pop()

上面的代码打印出像这样的树的深度优先搜索遍历

[3,2,1,4]

[3,2,5]

但是它只是打印这些值,我想将其存储在列表中,并想将列表返回为

[[3,2,1,4],[3,2,5]]。

我应该对代码进行哪些修改以实现此目的?

1 个答案:

答案 0 :(得分:0)

只需简单的修改就可以帮助您!

def traverse(node, result=[], path =[]):
    path.append(node.val)
    if len(node.children)==0:
        print(path)
        result.append(path.copy())
        path.pop()
    else:
        for child in node.children:
            traverse(child)
        path.pop()
    return result

将路径复制到一个名为“结果”的列表中并返回它。

相关问题