【问题标题】:Enumerating all paths in a tree枚举树中的所有路径
【发布时间】:2011-04-15 01:22:03
【问题描述】:

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

     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

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

【问题讨论】:

  • 所有图边都是双向的吗?
  • 那么你还期待 b-a、c-a、d-b、e-c、f-c、a-b-a、a-c-a、b-d-b、b-a-b、b-a-c 等?
  • @saus:哎呀抱歉。我没有注意到它。我的意思是定向的。

标签: python algorithm reference tree traversal


【解决方案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

【讨论】:

  • 您能否提供一个tree 的示例,您可以用它来调用paths() 来解决OP 的问题?
  • @Mike 我觉得不需要。最好使算法适应 OP 使用的任何数据结构,然后尝试猜测树实现的特定风格。
【解决方案2】:

还有一种方法:

树中没有重复的每条路径都由它的起点和终点唯一地描述。

所以枚举路径的一种方法是枚举每对可能的顶点。对于每一对,找到路径相对容易(找到共同的祖先并通过它)。

【讨论】:

    【解决方案3】:

    使用深度优先搜索找到树的每个节点的路径,然后调用enumerate-paths(Path p),其中p 是从根到节点的路径。假设路径p 是一个节点数组p[0] [1] .. p[n],其中p[0] 是根,p[n] 是当前节点。

    enumerate-paths(p) {
        for i = 0 .. n  
            output p[n - i] .. p[n] as a path. 
    }
    

    这些路径中的每一个都是不同的,并且它们中的每一个都不同于从树的任何其他节点返回的结果,因为没有其他路径以p[n] 结尾。显然它是完整的,因为任何路径都是从一个节点到它和根之间的某个节点。它也是最优的,因为它只找到并输出每条路径一次。

    顺序会与您的略有不同,但您始终可以创建一个路径列表数组,其中A[x] 是长度为x 的路径列表。然后您可以按长度顺序输出路径,尽管这需要 O(n) 存储。

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      相关资源
      最近更新 更多