簡體   English   中英

枚舉樹中的所有路徑

[英]Enumerating all paths in a tree

我想知道如何最好地實現樹數據結構,以便能夠枚舉所有級別的路徑。 讓我用下面的例子解釋一下:

     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

還有一個方法:

樹中沒有重復的每條路徑都由其開始和結束唯一描述。

因此,枚舉路徑的方法之一是枚舉每對可能的頂點。 對於每一對,找到路徑相對容易(找到共同的祖先並通過它)。

使用深度優先搜索找到樹的每個節點的路徑,然后調用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)存儲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM