簡體   English   中英

一棵樹的所有路徑

[英]All paths of a tree

如何使用遞歸列出一棵樹中的所有路徑?

我在外殼中稱其為:

t = Tree(1)
t2 = Tree(2)
t7 = Tree(7), t2.children = [t7]
t5 = Tree(5)
t9 = Tree(9)
t8 = Tree(8)
t5.children = [t8, t9]
t.children = [t5, t2]

基本上我把那棵樹做成這樣:

     1
   /   \
   2    5
   |    /\
   7   9  8

我想在列表中返回以下路徑:

[[1, 2, 7], [1, 5, 9], [1, 5, 8]]

總的來說,我可以列出清單,它只是找到一種方法來獲取我正在努力去做的特定路徑! 將不勝感激!

假設您的類結構與以下類似,則可以使用遞歸獲取所有路徑。

class Tree:
    def __init__(self, value):
        self.value = value
        self.children = []


def get_paths(t, paths=None, current_path=None):
    if paths is None:
        paths = []
    if current_path is None:
        current_path = []

    current_path.append(t.value)
    if len(t.children) == 0:
        paths.append(current_path)
    else:
        for child in t.children:
            get_paths(child, paths, list(current_path))
    return paths


t = Tree(1)
t2 = Tree(2)
t7 = Tree(7)
t2.children = [t7]
t5 = Tree(5)
t9 = Tree(9)
t8 = Tree(8)
t5.children = [t9, t8]
t.children = [t2, t5]

print get_paths(t)

輸出:

[[1, 2, 7], [1, 5, 9], [1, 5, 8]]

@Shashank感謝您猜測Tree的可能結構

這是一種使用完全不可變的對象,元組以及除樹本身外沒有任何參數的方法。 無需使用可變列表存儲狀態,我們只需沿鏈向上傳遞元組包裝的值即可。 get_paths必定每次都會返回一個元組的元組。

class Tree:
    def __init__(self, value):
        self.value = value
        self.children = ()


def get_paths(t):
    if t.children:
        return tuple((t.value,) + path 
            for child in t.children 
                for path in get_paths(child))
    else:
        return ((t.value,),)


t = Tree(1)
t2 = Tree(2)
t3 = Tree(3)
t4 = Tree(4)
t5 = Tree(5)
t6 = Tree(6)
t7 = Tree(7)
t8 = Tree(8)
t9 = Tree(9)
t.children = (t2, t5)
t2.children = (t7,)
t5.children = (t9, t8)
t9.children = (t6,t3,t4)

print(get_paths(t))

當然,傳遞可變列表來存儲狀態沒有錯,但是我相信這種解決方案更優雅,更實用。

要將其轉換為列表結構列表,只需執行以下操作:

paths = [list(path) for path in get_paths(t)]

或者只需將函數中的所有元組替換為列表,就可以了!

暫無
暫無

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

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