如何继续使用递归列出树中的所有路径?
我在shell中调用它:
t = Tree(1)
t2 = Tree(2)
t7 = Tree(7), t2.children = [t7]
t5 = Tree(5)
t9 = Tree(9)
t8 = Tree(8)
t5.children = [t8, t9]
t.children = [t5, t2]
基本上我把那棵树看成是这样的:
1
/ \
2 5
| /\
7 9 8
我想在列表中返回以下路径:
[[1, 2, 7], [1, 5, 9], [1, 5, 8]]
总的来说,我可以制作清单,它只是找到一种方法来获得我正在努力做的特定路径!非常感谢任何帮助!
答案 0 :(得分:2)
假设您的类结构类似于以下内容,那么您可以使用递归来获取所有路径。
class Tree:
def __init__(self, value):
self.value = value
self.children = []
def get_paths(t, paths=None, current_path=None):
if paths is None:
paths = []
if current_path is None:
current_path = []
current_path.append(t.value)
if len(t.children) == 0:
paths.append(current_path)
else:
for child in t.children:
get_paths(child, paths, list(current_path))
return paths
t = Tree(1)
t2 = Tree(2)
t7 = Tree(7)
t2.children = [t7]
t5 = Tree(5)
t9 = Tree(9)
t8 = Tree(8)
t5.children = [t9, t8]
t.children = [t2, t5]
print get_paths(t)
输出:
[[1, 2, 7], [1, 5, 9], [1, 5, 8]]
@Shashank感谢您猜测Tree
答案 1 :(得分:0)
除了树本身之外,还有一种方法是使用完全不可变的对象,元组和没有参数。我们只是沿着链向上传递元组包装的值,而不是使用可变列表来存储状态。 get_paths
每次都必须返回一个元组元组。
class Tree:
def __init__(self, value):
self.value = value
self.children = ()
def get_paths(t):
if t.children:
return tuple((t.value,) + path
for child in t.children
for path in get_paths(child))
else:
return ((t.value,),)
t = Tree(1)
t2 = Tree(2)
t3 = Tree(3)
t4 = Tree(4)
t5 = Tree(5)
t6 = Tree(6)
t7 = Tree(7)
t8 = Tree(8)
t9 = Tree(9)
t.children = (t2, t5)
t2.children = (t7,)
t5.children = (t9, t8)
t9.children = (t6,t3,t4)
print(get_paths(t))
当然,将可变列表传递给存储状态并没有错,但我相信这个解决方案更加优雅和实用。
要将其转换为列表结构列表,您只需执行以下操作:
paths = [list(path) for path in get_paths(t)]
或者只是用列表替换函数中的所有元组,你就可以了!