在Python中使用堆栈实现深度优先树遍历

时间:2018-12-12 13:34:56

标签: python json tree stack

如果给出位置的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
-Manhattan
San Francisco Bay Area
-San Francisco
-South Bay
--San Jose

遍历这些位置似乎很有意义,并且每当“ parent_id”为None时,我们都知道这是树的根,因此执行深度优先遍历。找到其子项(无论“ parent_id”等于该id的位置),使用堆栈跟踪它们并在每次/按字母顺序对节点的所有子项进行排序时递增级别。

您将如何实现这种树(节点+子级)的创建并通过堆栈遍历(同时跟踪级别-以便添加连字符和排序)?

您将直接遍历JSON并执行此过程,还是创建一个单独的结构实现和树,然后执行?对于其中的一些不同步骤,我们将不胜感激。我知道如何解决它,我只是不清楚确切的实现方式。

1 个答案:

答案 0 :(得分:2)

您可以按照以下步骤从给定的数据构建“树”:

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