目录
👑 王位继承顺序:模拟家族树的优雅解法(含 Python 实现)
👑 王位继承顺序:模拟家族树的优雅解法(含 Python 实现)
在某个神秘的王国中,国王制定了一条严格的 王位继承制度,每个人的地位不仅取决于出生顺序,还受到死亡状态的影响。这道题要求我们模拟一个家族树,并实现 birth
(出生)、death
(死亡)和 getInheritanceOrder
(获取当前合法继承顺序)三个功能。
本题不仅考察数据结构设计和递归逻辑,还训练我们如何高效地维护一棵“变化中的树”。本文将带你从题目背景入手,逐步分析建模方法与 Python 实现,并提供详尽的案例分析。
🧾 题目描述
王国由一个国王开始,随着时间的推移,家族成员不断扩张(出生),也会有人去世(死亡)。王国有一个唯一的 继承顺序,继承顺序满足以下规则:
- 第一继承人永远是国王;
- 一个父亲的所有孩子按出生顺序排列;
- 死亡人员仍会保留其在继承链中的位置,只是在最终输出中被跳过;
- 每个成员最多调用一次
birth
来添加孩子,可以多次调用death
,但不会重复死亡。
你需要实现以下功能:
类定义:
class ThroneInheritance:
def __init__(self, kingName: str): ...
def birth(self, parentName: str, childName: str): ...
def death(self, name: str): ...
def getInheritanceOrder(self) -> List[str]: ...
🧠 解题思路分析
👨👩👧👦 家谱建模 —— 树结构
每个人及其孩子可以看作一棵 树,其中:
- 每个节点是一个人;
- 每个节点维护一个有序的孩子列表;
- 我们可以使用 前序遍历(Preorder DFS) 来模拟王位继承顺序;
- 只需用一个集合记录死亡成员,避免他们出现在最终输出中即可。
🔄 操作行为分析
birth(parent, child)
:只需在parent
的孩子列表中追加child
。death(name)
:只需将name
加入死亡集合
。getInheritanceOrder()
:从king
开始前序遍历整棵树,忽略死亡成员。
🛠️ 数据结构设计
变量名 | 类型 | 描述 |
|
| 国王的名字 |
|
| 每个人名对应的孩子有序列表 |
|
| 死亡人员集合 |
🧩 代码实现(Python)
from typing import List
class ThroneInheritance:
def __init__(self, kingName: str):
self.king = kingName
self.children = {kingName: []} # 每个人名对应的孩子列表
self.dead = set() # 存储已死亡的人的名字
def birth(self, parentName: str, childName: str) -> None:
if parentName not in self.children:
self.children[parentName] = []
self.children[parentName].append(childName)
self.children[childName] = [] # 初始化新孩子的孩子列表为空
def death(self, name: str) -> None:
self.dead.add(name)
def getInheritanceOrder(self) -> List[str]:
order = []
def dfs(person):
if person not in self.dead:
order.append(person)
for child in self.children.get(person, []):
dfs(child)
dfs(self.king)
return order
🔍 示例说明
t = ThroneInheritance("king")
t.birth("king", "andy")
t.birth("king", "bob")
t.birth("king", "catherine")
t.birth("andy", "matthew")
t.birth("bob", "alex")
t.birth("bob", "asha")
print(t.getInheritanceOrder())
# 输出: ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob")
print(t.getInheritanceOrder())
# 输出: ["king", "andy", "matthew", "alex", "asha", "catherine"]
👁️ 结构可视化:
king
/ | \
andy bob catherine
| / \
matthew alex asha
若 bob 死亡,他仍在树中,只是不出现在输出顺序里。
⏱️ 复杂度分析
方法 | 时间复杂度 | 空间复杂度 |
| O(1) | O(1) |
| O(1) | O(1) |
| O(N) | O(N)(递归栈 + 结果) |
其中 N
是目前为止出生过的成员总数。
🔄 可选优化与扩展思路
- 支持查询某人是否活着;
- 支持查询某人当前在继承序列中的排名;
- 可用队列代替递归以避免栈溢出(超大树);
- 实现图形化可视化(例如网页显示家族树);
✅ 总结
本题是一道模拟题,但它对树的遍历、数据建模和继承逻辑的理解都提出了较高的要求。我们使用前序 DFS 与字典集合结构,简洁高效地完成了需求。
本题关键点:
- 正确维护每个人的孩子列表;
- 利用递归生成继承顺序;
- 将死亡状态单独记录,不修改结构;