python - 如何查找从根到节点的路径(python 3.6)
问题描述
我试图找到从 ROOT 到某个 VALUE 的节点的树的所有路径。
我尝试的第一个解决方案是使用当节点的值 == 值时停止的递归:
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] 值。
非常感谢有关如何返回预期输出的指导。
解决方案
还附加树类的代码:
class Tree:
def __init__(self, label, branches=[]):
for b in branches:
assert isinstance(b, Tree)
self.label = label
self.branches = list(branches)
def is_leaf(self):
return not self.branches
推荐阅读
- javascript - 我的 Node 和 express 应用程序在错误处理中间件时没有收到 req.session?
- javascript - 如何在 React 中实现文本转语音
- phpunit - Laravel 测试 - 该名称已被使用
- python-3.x - 解析数据框列中的 json
- javascript - React Native Chart Kit - 条形图颜色从上到下淡出每个条形图
- python - 如何在 Python 中使用 Matplotlib 绘制时间线图?
- python - Python github 使用用户名和密码拉取
- android - Google Play 控制台读取的 .Keystore 值与 Keytool 不同
- vue.js - NuxtJS - 我想知道如何为特定页面实现加载
- dpdk - Packet gen dpdk 文件发送终端命令