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

时间:2018-07-22 15:31:51

标签: 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)

1 个答案:

答案 0 :(得分:3)

遵循以下几行的递归方法应该起作用:

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