枚举树中的所有路径
我想知道如何最好地实现树数据结构,以便能够枚举所有级别的路径。让我用以下示例进行解释:
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
到目前为止,我正在使用字典构建的数据结构上执行不同深度的深度优先搜索,并记录所看到的唯一节点但我想知道是否有更好的方法来进行这种遍历。有什么建议吗?
I was wondering how to best implement a tree data structure to be able to enumerate paths of all levels. Let me explain it with the following example:
A
/ \
B C
| /\
D E F
I want to be able to generate the following:
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
As of now, I am executing a depth-first-search for different depths on a data structure built using a dictionary and recording unique nodes that are seen but I was wondering if there is a better way to do this kind of a traversal. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每当你在树上发现问题时,只需使用递归即可:D
Whenever you find a problem on trees, just use recursion :D
还有一种方式:
树中每条没有重复的路径都由其起点和终点唯一地描述。
因此,枚举路径的方法之一是枚举每对可能的顶点。对于每一对来说,找到路径相对容易(找到共同的祖先并遍历它)。
Just one more way:
Every path without repetitions in tree is uniquely described by its start and finish.
So one of ways to enumerate paths is to enumerate every possible pair of vertices. For each pair it's relatively easy to find path (find common ancestor and go through it).
使用深度优先搜索找到到树的每个节点的路径,然后调用 enumerate-paths(Path p) ,其中 p 是从根到节点的路径。假设路径
p
是节点p[0] [1] .. p[n]
的数组,其中p[0]
是根节点,p[n]
是当前节点。这些路径中的每一个都是不同的,并且它们中的每一个都与从树的任何其他节点返回的结果不同,因为没有其他路径以
p[n]
结尾。显然它是完整的,因为任何路径都是从一个节点到它与根之间的某个节点。它也是最优的,因为它只查找并输出每条路径一次。该顺序与您的顺序略有不同,但您始终可以创建一个路径列表数组,其中
A[x]
是长度为x
的路径列表。然后,您可以按照路径长度的顺序输出路径,尽管这将占用 O(n) 存储空间。Find a path to each node of the tree using depth first search, then call
enumerate-paths(Path p)
, wherep
is the path from the root to the node. Let's assume that a pathp
is an array of nodesp[0] [1] .. p[n]
wherep[0]
is the root andp[n]
is the current node.Each of these paths is different, and each of them is different from the results returned from any other node of the tree since no other paths end in
p[n]
. Clearly it is complete, since any path is from a node to some node between it and the root. It is also optimal, since it finds and outputs each path exactly once.The order will be slightly different from yours, but you could always create an array of list of paths where
A[x]
is a List of the paths of lengthx
. Then you could output the paths in order of their length, although this would take O(n) storage.