python3 - 遍历树并获取所有叶节点兄弟集

问题描述 投票:-2回答:1

我有一个json文件,其结构就像一个嵌套树:

{
    "sub": [
    {
        "code": "01",
        "name": "a"
    },
    {
        "code": "02",
        "name": "b",
        "sub": [
        {
            "code": "0201",
            "name": "b1"
        },
        {
            "code": "0202",
            "name": "b2",
            "sub":[{
                "code": "020201",
                "name": "b21"
            },{
                "code": "020202",
                "name": "b22"
            }]
        }]
    },
    {
        "code": "03",
        "name": "c",
        "sub": [
        {
            "code": "0301",
            "name": "c1"
        },
        {
            "code": "0302",
            "name": "c2"
        }]
    }]
}

我想要一个算法来获取叶节点兄弟的所有集合(只需要name属性)。在上面的例子中应该返回:

[
 ['a'],
 ['b1'],
 ['b21','b22'],
 ['c1','c2']
]

请注意,每个元素都是叶节点,每个组中的节点都是兄弟节点。

我怎样才能在python3.x中实现它?

def traverse(tree):
    #how to implement this function?

with open('demo.json') as f:
    tree = json.load(f)
    traverse(tree)
python-3.x algorithm tree-traversal
1个回答
1
投票

您可以递归地实现此操作:检查当前树是否具有子节点,然后收集并生成叶子的所有子节点的名称。然后,只需递归每个子节点。

def traverse(tree):
    if "sub" in tree:
        yield [sub["name"] for sub in tree["sub"] if "sub" not in sub]
        for sub in tree["sub"]:
            yield from traverse(sub)
© www.soinside.com 2019 - 2024. All rights reserved.