简体   繁体   English

返回 n 叉树中从根到叶的所有路径

[英]RETURN all paths from root to leaf in n-ary tree

There's a lot out there about how to print all paths from root to leaf in a tree, but I'm trying to return them.关于如何打印树中从根到叶的所有路径有很多,但我正在尝试返回它们。 Each node has a list of children, and I need to return a list of strings where each string represents a path.每个节点都有一个子节点列表,我需要返回一个字符串列表,其中每个字符串代表一个路径。 Ie with the tree即与树

   A
  /\
  B F
/ | \
C D  E 

I should return ['A, B, C', 'A,B,D', 'A,B,E', 'A,F'] The function must be recursive and done in python.我应该返回 ['A, B, C', 'A,B,D', 'A,B,E', 'A,F'] function 必须是递归的并在 python 中完成。 I've tried this function for a while, but am getting stuck wrapping my head around the recursion.我已经尝试了这个 function 一段时间,但我被困在递归周围。 Ie if my function starts with path="", then every time I recall the function I lose that path...即,如果我的 function 以 path="" 开头,那么每次我回忆起 function 时,我都会丢失那条路径...

*Edit: solved with help from @flakes's answer and modifying yield [root.value] + path to yield [root.value+", "+path[0]) *编辑:在@flakes的回答和修改yield [root.value] + path to yield [root.value+", "+path[0])的帮助下解决

Start by defining a class for your node structure.首先为您的节点结构定义 class。 It should have a value, and a list of child nodes:它应该有一个值和一个子节点列表:

class Node:
    def __init__(self, value, children=None):
        self.value = value
        self.children = children or []

For returning data from recursive functions, I like to use generators as they can simplify the logic a lot.对于从递归函数返回数据,我喜欢使用生成器,因为它们可以大大简化逻辑。

The first use case is when there are no children.第一个用例是没有孩子的时候。 The result should be [value] .结果应该是[value]

When there are children, you want to loop each child in the children list, find their respective paths, and for each path, append the current [value] to their result.当有孩子时,你想循环孩子列表中的每个孩子,找到他们各自的路径,并且对于每个路径,append 当前[value]到他们的结果。

You might get something like this:你可能会得到这样的东西:

def find_paths(root):
    if len(root.children) == 0:
        yield [root.value]

    for child in root.children:
        for path in find_paths(child):
            yield [root.value] + path

Test case:测试用例:

tree = Node('a', [Node('b', [Node('c'), Node('d'), Node('e')]), Node('f')])

for path in find_paths(tree):
    print(path)
['a', 'b', 'c']
['a', 'b', 'd']
['a', 'b', 'e']
['a', 'f']

If you need it as one flat list, then I would just flatten the result after the call:如果您需要将其作为一个平面列表,那么我将在通话后将结果展平:

output = [value for path in find_paths(tree) for value in path]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM