王位继承顺序

标签: 深度优先搜索 设计 哈希表

难度: Medium

一个王国里住着国王、他的孩子们、他的孙子们等等。每一个时间点,这个家庭里有人出生也有人死亡。

这个王国有一个明确规定的王位继承顺序,第一继承人总是国王自己。我们定义递归函数 Successor(x, curOrder) ,给定一个人 x 和当前的继承顺序,该函数返回 x 的下一继承人。

Successor(x, curOrder):
    如果 x 没有孩子或者所有 x 的孩子都在 curOrder 中:
        如果 x 是国王,那么返回 null
        否则,返回 Successor(x 的父亲, curOrder)
    否则,返回 x 不在 curOrder 中最年长的孩子

比方说,假设王国由国王,他的孩子 Alice 和 Bob (Alice 比 Bob 年长)和 Alice 的孩子 Jack 组成。

  1. 一开始, curOrder 为 ["king"].
  2. 调用 Successor(king, curOrder) ,返回 Alice ,所以我们将 Alice 放入 curOrder 中,得到 ["king", "Alice"] 。
  3. 调用 Successor(Alice, curOrder) ,返回 Jack ,所以我们将 Jack 放入 curOrder 中,得到 ["king", "Alice", "Jack"] 。
  4. 调用 Successor(Jack, curOrder) ,返回 Bob ,所以我们将 Bob 放入 curOrder 中,得到 ["king", "Alice", "Jack", "Bob"] 。
  5. 调用 Successor(Bob, curOrder) ,返回 null 。最终得到继承顺序为 ["king", "Alice", "Jack", "Bob"] 。

通过以上的函数,我们总是能得到一个唯一的继承顺序。

请你实现 ThroneInheritance 类:

  • ThroneInheritance(string kingName) 初始化一个 ThroneInheritance 类的对象。国王的名字作为构造函数的参数传入。
  • void birth(string parentName, string childName) 表示 parentName 新拥有了一个名为 childName 的孩子。
  • void death(string name) 表示名为 name 的人死亡。一个人的死亡不会影响 Successor 函数,也不会影响当前的继承顺序。你可以只将这个人标记为死亡状态。
  • string[] getInheritanceOrder() 返回 除去 死亡人员的当前继承顺序列表。

示例:

输入:
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
输出:
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]

解释:
ThroneInheritance t= new ThroneInheritance("king"); // 继承顺序:king
t.birth("king", "andy"); // 继承顺序:king > andy
t.birth("king", "bob"); // 继承顺序:king > andy > bob
t.birth("king", "catherine"); // 继承顺序:king > andy > bob > catherine
t.birth("andy", "matthew"); // 继承顺序:king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // 继承顺序:king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // 继承顺序:king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // 继承顺序:king > andy > matthew > bob(已经去世)> alex > asha > catherine
t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "alex", "asha", "catherine"]

提示:

  • 1 <= kingName.length, parentName.length, childName.length, name.length <= 15
  • kingNameparentName, childName 和 name 仅包含小写英文字母。
  • 所有的参数 childName 和 kingName 互不相同
  • 所有 death 函数中的死亡名字 name 要么是国王,要么是已经出生了的人员名字。
  • 每次调用 birth(parentName, childName) 时,测试用例都保证 parentName 对应的人员是活着的。
  • 最多调用 105 次birth 和 death 。
  • 最多调用 10 次 getInheritanceOrder 。

Submission

运行时间: 289 ms

内存: 63.8 MB

class ThroneInheritance:
    def __init__(self, kingName):
        self.hash = defaultdict(list)
        self.king = kingName
        self.dead = set()

    def birth(self, parentName, childName):
        self.hash[parentName].append(childName)

    def death(self, name):
        self.dead.add(name)

    def getInheritanceOrder(self):
        res = list()

        def preOrder(root):
            if root not in self.dead:
                res.append(root)
            if root in self.hash:
                for child in self.hash[root]:
                    preOrder(child)
        preOrder(self.king)
        return res

# Your ThroneInheritance object will be instantiated and called as such:
# obj = ThroneInheritance(kingName)
# obj.birth(parentName,childName)
# obj.death(name)
# param_3 = obj.getInheritanceOrder()

Explain

该题解采用了树形数据结构来模拟继承关系,使用散列表(hash)存储每个人与其孩子们的关系,以及一个集合(dead)记录死亡人员。当调用birth函数时,孩子会被添加到对应父母的列表中。death函数只将人标记为死亡,不从树中删除。继承顺序是通过先序遍历(preOrder)树来得到的,同时在遍历过程中跳过标记为死亡的人。

时间复杂度: O(n)

空间复杂度: O(n)

# 类定义及初始化
class ThroneInheritance:
    def __init__(self, kingName):
        self.hash = defaultdict(list)  # 存储每个人与其孩子的映射
        self.king = kingName  # 国王的名字
        self.dead = set()  # 记录已死亡人员的集合

    # 记录新的出生
    def birth(self, parentName, childName):
        self.hash[parentName].append(childName)  # 在父名下添加孩子名

    # 记录人员死亡
    def death(self, name):
        self.dead.add(name)  # 将名字加入死亡记录

    # 获取当前的继承顺序,不包括已死亡人员
    def getInheritanceOrder(self):
        res = []  # 存储继承顺序的结果列表

        def preOrder(root):  # 递归函数进行先序遍历
            if root not in self.dead:  # 如果当前人未死亡,加入结果列表
                res.append(root)
            if root in self.hash:  # 遍历当前人的每个孩子
                for child in self.hash[root]:
                    preOrder(child)

        preOrder(self.king)  # 从国王开始遍历
        return res  # 返回继承顺序

# 使用示例
# obj = ThroneInheritance('kingName')
# obj.birth('parentName', 'childName')
# obj.death('name')
# param_3 = obj.getInheritanceOrder()

Explore

在`ThroneInheritance`类的`birth`函数中,每当添加一个孩子时,该孩子被添加到父亲名下的列表的末尾。由于列表是保持元素添加顺序的数据结构,因此孩子的出生顺序被自然记录下来。继承顺序的遍历(即先序遍历)时,将会按照这个顺序访问孩子,确保了继承顺序的正确性。

将人标记为死亡而不从树结构中直接删除有几个优势:首先,这样可以避免修改树的结构,维护简单,尤其在涉及到复杂的父子关系时;其次,这种方式可以快速地标记一个人的死亡状态,并且在生成继承顺序时通过简单地检查死亡集合来跳过这些人,这样可以在不重新构建树的情况下快速更新继承顺序;最后,即使某些成员已经标记为死亡,他们的存在仍可能对理解整个家族树的结构和后续操作有用。

当死亡人数较多时,这种处理方式确实可能影响遍历的效率。因为即使一个人已经死亡,其下的所有子孙还是会被递归遍历一遍,只是在添加到结果列表时被跳过。这意味着如果大量的人已经死亡,尤其是在树的上层,仍然需要进行大量的无效遍历。尽管如此,由于不需要重构树,这种方式在实现简单性和避免频繁修改树结构的情况下还是有其效率和实用性。

选择使用散列表来存储每个人的孩子列表主要是因为散列表提供了快速的查找、插入和删除操作。在继承树中,可能需要频繁地查找某个人的孩子或向某个人的孩子列表中添加新的孩子,散列表使这些操作的时间复杂度平均为O(1)。而如果使用链表,虽然插入操作快速,但查找特定人的孩子需要O(n)的时间复杂度;二叉树提供了较好的平衡查找性能,但对于动态变化的大家族树来说,可能会面临频繁的重平衡问题。因此,散列表在这种用例中提供了一种既快速又简单的解决方案。