枚举树中的所有路径

枚举树中的所有路径,第1张

枚举树中的所有路径

每当您在树上发现问题时,只需使用递归:D

def paths(tree):  #Helper function  #receives a tree and   #returns all paths that have this node as root and all other paths  if tree is the empty tree:    return ([], [])  else: #tree is a node    root = tree.value    rooted_paths = [[root]]    unrooted_paths = []    for subtree in tree.children:        (useable, unueseable) = paths(subtree)        for path in useable: unrooted_paths.append(path) rooted_paths.append([root]+path)        for path in unuseable: unrooted_paths.append(path)    return (rooted_paths, unrooted_paths)def the_function_you_use_in_the_end(tree):   a,b = paths(tree)   return a+b


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5643266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存