使用递归算法遍历每个人的子孙节点,并统计人数。
示例代码如下:
class Person:
def __init__(self, name, children=None):
self.name = name
if children is None:
self.children = []
else:
self.children = children
def count_descendants(person):
count = 0
for child in person.children:
count += count_descendants(child)
return 1 + count
# 构造一个样例家族谱
a = Person("A")
b = Person("B")
c = Person("C")
d = Person("D")
e = Person("E")
f = Person("F")
g = Person("G")
h = Person("H")
a.children = [b, c, d]
b.children = [e, f]
c.children = [g, h]
# 统计A的后代人数
n = count_descendants(a) - 1
print(f"A的后代人数为:{n}")
输出:
A的后代人数为:7
其中,count_descendants(person)
函数是递归遍历某一个人及其所有子孙节点,并计算其数量的函数。在主函数中,我们对家族谱构造完毕后的树状结构进行遍历,求出根节点A的子孙人数,并输出结果。由于A本身也是家族成员中的一员,所以最后结果需减1。