gpt4 book ai didi

python - 枚举树中的所有路径

转载 作者:太空狗 更新时间:2023-10-29 21:44:33 24 4
gpt4 key购买 nike

我想知道如何最好地实现树数据结构,以便能够枚举所有级别的路径。让我用下面的例子来解释它:

     A
/ \
B C
| /\
D E F

我希望能够生成以下内容:

A
B
C
D
E
F
A-B
A-C
B-D
C-E
C-F
A-B-D
A-C-E
A-C-F

截至目前,我正在对使用字典构建的数据结构执行不同深度的深度优先搜索,并记录看到的唯一节点,但我想知道是否有更好的方法来执行这种操作遍历。有什么建议吗?

最佳答案

每当你在树上发现问题时,就使用递归 :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

关于python - 枚举树中的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5671486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com