python - Python:获取树中所有可能路径的列表?
问题描述
我有一棵树,例如看起来像这样
(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 - 如何使用 Shift() 和 Apply() 函数来遍历行?
- flutter - 如何在颤动中找到或创建 private.pem 和 public.pem
- laravel - 将变量(不是属性)传递给 laravel 工厂创建方法
- android - 反应输入 onKeyDown/onKeyUp Android Chrome
- java - 选择两个大小相等的不相交子数组 A 和 B,使总和最大化 (A_1*B_k + A_2*B_(k-1) ... + A_k*B_1), k = |A| = |B|
- javascript - 退格键按下时过滤器不起作用
- javascript - React Router 总是渲染 NotFound 默认组件
- c# - 玩家边界实现和代码审查
- javascript - JavaScript:变量在等待中未定义
- python - MinMaxScaler 的奇怪输出