如何使用Python找到303和321个体的最新共同祖先?

时间:2015-11-18 03:08:22

标签: python binary-tree ancestor

使用以下二叉树,如何使用Python找到303和321个体的最新共同祖先?

def preprocess(family_list):
descent_dict = collections.defaultdict(list)
for person in family_list:
    descent_dict[person["parent"]].append(person["name"])
return descent_dict

def print_family_tree(descent_dict, people, depth=0):
for person in people:
    print("  "*depth+person)
    print_family_tree(descent_dict, descent_dict[person], depth+1)

family = [
{'name': '303', 'parent': ''},
{'name': '301', 'parent': '303'},
{'name': '101', 'parent': '303'},
{'name': '0', 'parent': '101'},
{'name': '0', 'parent': '101'},
{'name': '2', 'parent': '301'},
{'name': '1', 'parent': '301'},
{'name': '0', 'parent': '2'},
{'name': '0', 'parent': '2'},
{'name': '0', 'parent': '1'},
{'name': '0', 'parent': '1'},
{'name': '322', 'parent': ''},
{'name': '105', 'parent': '322'},
{'name': '321', 'parent': '322'},
{'name': '0', 'parent': '105'},
{'name': '0', 'parent': '105'},
{'name': '103', 'parent': '321'},
{'name': '315', 'parent': '321'},
{'name': '2', 'parent': '315'},
{'name': '1', 'parent': '315'},
{'name': '0', 'parent': '2'},
{'name': '0', 'parent': '2'},
{'name': '0', 'parent': '1'},
{'name': '0', 'parent': '1'}
]

d = preprocess(family)
print_family_tree(d, d[''])

0 个答案:

没有答案