如何从特定节点获取树祖先列表?

时间:2017-02-27 22:41:43

标签: python python-3.x tree ancestor

给定一个树,其中每个节点可以有N个子节点,但只有1个父节点。如何获得一个节点的祖先?例如,假设我得到了这棵树:

#  Operator
# ... FooOperator
# ...... BOperator
# ......... B1Operator
# ............ B11Operator
# ...... AOperator
# ......... A2Operator
# ......... A1Operator
# ......... A3Operator
# ...... COperator
# ......... C1Operator
# ......... C2Operator
# ............ C21Operator

tree = {
    'children': [{
        'children': [{
            'children': [{
                'children': [{
                    'children': [],
                    'class': 'B11Operator',
                    'parent': 'B1Operator'
                }],
                'class': 'B1Operator',
                'parent': 'BOperator'
            }],
            'class': 'BOperator',
            'parent': 'FooOperator'
        },{
        'children': [{
            'children': [],
            'class': 'A2Operator',
            'parent': 'AOperator'
        },{
            'children': [],
            'class': 'A1Operator',
            'parent': 'AOperator'
        },{
            'children': [],
            'class': 'A3Operator',
            'parent': 'AOperator'
        }],
        'class': 'AOperator',
        'parent': 'FooOperator'},{
        'children': [{
            'children': [],
            'class': 'C1Operator',
            'parent': 'COperator'
        },{
            'children': [{
                'children': [],
                'class': 'C21Operator',
                'parent': 'C2Operator'
            }],
            'class': 'C2Operator',
            'parent': 'COperator'
        }],
        'class': 'COperator',
        'parent': 'FooOperator'
    }],
    'class': 'FooOperator',
    'parent': 'Operator'
    }],
     'class': 'Operator',
     'parent': None
}

def display_tree(node, indent=0):
    print('.' * indent, node['class'])
    indent += 3
    for child in node['children']:
        display_tree(child, indent)

display_tree(tree)

您如何从"C21Operator"获取祖先列表,例如结果为["Operator", "FooOperator", "COperator", "C2Operator", "C21Operator"]

1 个答案:

答案 0 :(得分:0)

鉴于您的数据结构,我认为只有一个强力解决方案是可能的:

In [6]: def path_to_child(tree, target, acc=None):
   ...:     if acc is None:
   ...:         acc = []
   ...:     if tree['class'] == target:
   ...:         return acc
   ...:     for child in tree['children']:
   ...:         found = path_to_child(child, target, acc + [tree['class']])
   ...:         if found is not None:
   ...:             return found
   ...:

In [7]: path_to_child(tree, 'C21Operator')
Out[7]: ['Operator', 'FooOperator', 'COperator', 'C2Operator']

In [8]:

如果您知道目标的位置,您可以更智能地遍历树。