Python:获取树中所有可能路径的列表?

标签 python recursion tree

我有一棵树,例如看起来像这样

 (0, 1)
    (2, 3)
       (4, 5)
          (6, 7)
          (6, 3)
       (4, 1)
          (6, 3)

当我用这种方法打印时:

def deep_print(self, d=0):
    if self == None:
        return

    print("   "*d, self.value)

    for child in self.children:
        child.deep_print(d + 1)

现在我想要一个方法,它可以为我提供一个包含所有可能的叶子路径的列表。所以在这种情况下输出应该是:

[[(0,1),(2,3),(4,5),(6,7)], [(0,1),(2,3),(4,5),(6,3)], [(0,1),(2,3),(4,1),(6,3)]]

编辑: 这是我的树的结构

class Tree:
    def __init__(self, value, d = 0):
        self.value = value
        self.children = []

    def add_child(self, child):
        self.children.append(child)

    def deep_print(self, d=0):
        if self == None:
            return
        print("   "*d, self.value)
        for child in self.children:
            child.deep_print(d + 1)

最佳答案

按照以下几行的递归方法应该有效:

def paths(self):
    if not self.children:
        return [[self.value]]  # one path: only contains self.value
    paths = []
    for child in self.children:
        for path in child.paths():
            paths.append([self.value] + path)
    return paths

关于Python:获取树中所有可能路径的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466610/

相关文章:

ajax - 使用 primefaces p :tabView, 使用 p :ajax doesn't work fine. 刷新选项卡 第一次刷新,但下次不刷新

python - tensorflow 1.13如何安全使用tf.searchsort?

python - 如何区分同一try语句中发生的不同异常

python - openCV imshow 随机失败

连接四-评价比较-c

filter - IcCube - 没有滚动条且元素数量有限的树过滤器

algorithm - 在完美二叉树中获取顶点的父节点

python - matplotlib slider 重绘不更新图文

php - 压缩主文件夹,里面有子文件夹

python - 如何解决这个复杂的递归问题,金字塔点系统