Python:获取树中所有可能路径的列表?
例如,我有一棵树,它看起来像这样Python:获取树中所有可能路径的列表?,python,recursion,tree,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.childr
(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
child.path()是什么意思?
child.path()
(复数)是通过子树获取路径的递归调用。树的结构具体如何?作为二叉树、嵌套列表或字典?当前发布的结构有点不清楚。@Ajax1234self.children
,递归调用表示子树列表/iterable。