【发布时间】:2020-09-10 02:33:01
【问题描述】:
我正在尝试查找某个 VALUE 的树从 ROOT 到 NODE 的所有路径。
我尝试的第一个解决方案是使用当节点的值 == 值时停止的递归:
def list_paths_to_value(t, value):
list_ = []
for b in t.branches:
list_ += [[t.label] + path for path in list_paths_to_value(b, value)]
if t.label == value:
return [[t.label]]
return list_
one_branch_two_depth = Tree(1, [Tree(2, [Tree(2)])])
list_paths_to_value(one_branch_two_depth, 2)
Output:
[[1,2]]
输出应该是 [[1,2], [1,2,2]] 但我的输出无法返回 [1,2,2] 路径。
我的另一个解决方案是强制递归函数只在树的叶子处停止:
def list_paths_to_value(t, value):
list_ = []
for b in t.branches:
list_ += [[t.label] + path for path in list_paths_to_value(b, value)]
if t.label == value and t.is_leaf():
return [[t.label]]
return list_
one_branch_two_depth = Tree(1, [Tree(2, [Tree(2)])])
list_paths_to_value(one_branch_two_depth, 2)
Output:
[[1,2,2]]
另一方面,这并没有返回 [1,2] 值。
非常感谢有关如何返回预期输出的指导。
【问题讨论】:
标签: python python-3.x recursion tree