亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中使用堆棧實現深度優先樹遍歷

在 Python 中使用堆棧實現深度優先樹遍歷

狐的傳說 2021-09-14 20:47:52
如果給出位置的 JSON 列表,例如:locations = [  {"id": 1, "name": "San Francisco Bay Area", "parent_id": None},  {“id": 2, "name": "San Jose", "parent_id": 3},  {"id": 3, "name": "South Bay", "parent_id": 1},  {"id": 4, "name": "San Francisco", "parent_id": 1},  {"id": 5, "name": "Manhattan", "parent_id": 6},  {"id": 6, "name": "New York", "parent_id": None}]我希望能夠生成位置列表,子位置在其父位置下分組,并按字母順序排列,還用連字符縮進子位置。每個深度級別應按字母順序排序,最多可以有 5 個深度級別。所以上面的輸出將是:New York-ManhattanSan Francisco Bay Area-San Francisco-South Bay--San Jose似乎遍歷這些位置是有意義的,每當“parent_id”為 None 時,我們就知道這是樹的根,因此執行深度優先遍歷。找到它的孩子(只要“parent_id”等于這個 id),使用堆棧來跟蹤它們并每次遞增級別/對節點的所有孩子按字母順序排序。您將如何實現樹的創建(節點+子節點)并使用堆棧進行遍歷(同時跟蹤級別-能夠添加連字符-和排序)?您會直接遍歷 JSON 并執行此過程,還是創建一個單獨的結構工具和樹然后執行此操作?希望為其中一些不同步驟提供一些代碼 - 我知道如何解決它,我只是不清楚確切的實現。
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

您可以根據給定的數據構建此“樹”,如下所示:


locations = [

    {"id": 1, "name": "San Francisco Bay Area", "parent_id": None},

    {"id": 2, "name": "San Jose", "parent_id": 3},

    {"id": 3, "name": "South Bay", "parent_id": 1},

    {"id": 4, "name": "San Francisco", "parent_id": 1},

    {"id": 5, "name": "Manhattan", "parent_id": 6},

    {"id": 6, "name": "New York", "parent_id": None}

]


def find_children(parent, locations):

    branch = {}

    for location in locations:

        if location["parent_id"] == parent:

            children = find_children(location["id"], locations)

            branch[location["name"]] = children

    return branch


tree = find_children(None, locations)

print(tree)

哪個打印


{'San Francisco Bay Area': {'San Francisco': {}, 'South Bay': {'San Jose': {}}}, 'New York': {'Manhattan': {}}}

然后,您可以對以下內容進行排序和打印tree:


def print_tree(tree, level=0):

    branches = sorted(list(tree.keys()))

    for branch in branches:

        print("-" * level + branch)

        print_tree(tree[branch], level + 1)


print_tree(tree)

哪個打印


New York

-Manhattan

San Francisco Bay Area

-San Francisco

-South Bay

--San Jose


查看完整回答
反對 回復 2021-09-14
  • 1 回答
  • 0 關注
  • 297 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號