簡體   English   中英

鑒於我將所有直接連接的節點作為字典中的列表,如何打印二叉樹的所有可能路徑?

[英]How to print all possible paths of a binary tree given that I have all directly connected nodes as a list in a dictionary?

我有一棵帶有節點的樹: [1,2,3,4,5] 以 1 為根。 可以表示為:

在此處輸入圖像描述

我有一個字典,其中有鍵作為節點,它們包含一個連接到它們的節點列表,

my_dict = {1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}

從這本字典中,我想打印從根到葉節點的所有可能路徑,如下所示:

output: [[1,2,4],[1,2,5],[1,3]]

我試過的是,

l = list()
root = 1
def path_finder(root):
    l.append(root)
    prev = root
    for val in my_dict[root]:
        print(val)
        path_finder(val)
        if root == prev:
            print("End of path")

返回:

2
4
End of path
5
End of path
End of path
3
End of path

我完全堅持這一點,任何幫助將不勝感激。 提前致謝:-)

您可以使用遞歸生成器:

my_dict = {1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}
def get_paths(s, c = []):
  if not my_dict[s]:
     yield c+[s]
  else:
     for i in my_dict[s]:
       yield from get_paths(i, c+[s])

print(list(get_paths(1)))

Output:

[[1, 2, 4], [1, 2, 5], [1, 3]]

暫無
暫無

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

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