1 回答
TA贡献1845条经验 获得超8个赞
pop完成访问节点后不要忘记从当前路径
如果遇到“叶子”(不是键的节点 ID),则在输出列表中存储当前路径的副本
警惕损坏的数据,例如循环链接 - 将有助于保留set访问过的节点
上面的示例实现:
def get_source(root, dict_input):
# output list
path_list = []
# current path
cur_path = []
# visited set
visited = set()
# internal recursive helper function
def helper(node):
cur_path.append(node)
# normal node
if node in dict_input:
if not node in visited:
visited.add(node)
for child in dict_input[node]:
helper(child)
# else: cycle detected, raise an exception?
# leaf node
else:
# important: must be a copy of the current path
path_list.append(list(cur_path))
cur_path.pop()
# call this helper function on the root node
helper(root)
return path_list
测试:
>>> dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}
>>> get_source('C411', dict_input)
[['C411', 'C052', 'C001', '9001'], ['C411', 'C052', 'C002', '9002']]
添加回答
举报