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

时间:2017-12-21 07:49:34

标签: python-3.x algorithm tree-traversal

我有一个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)

1 个答案:

答案 0 :(得分: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)