Problem Description
Implement a ThroneInheritance class that simulates the inheritance order of a royal family. The order starts with the king and follows a depth-first (preorder) traversal of the family tree, giving priority to older children. The twist is that when a person dies, they are skipped in the inheritance order, although their descendants still remain in the order. The design must support adding new children, marking individuals as dead, and retrieving the current inheritance order (skipping dead individuals).
Key Insights
- Model the family hierarchy as a tree where nodes represent family members and edges represent parent-child relationships.
- Use a hash table to map a parent's name to a list of their children, preserving the order of birth.
- Maintain a set of dead members to quickly check if a person should be included in the inheritance order.
- The inheritance order can be obtained by performing a depth-first (preorder) traversal of the tree.
- Operations birth and death are efficient (O(1)), while getInheritanceOrder performs a full tree traversal (O(n)).
Space and Time Complexity
Time Complexity:
- birth: O(1)
- death: O(1)
- getInheritanceOrder: O(n) in the worst-case, where n is the number of family members.
Space Complexity:
- O(n) to store the tree structure and the set of dead members.
Solution
We use a tree (implemented as a dictionary/hash table) to maintain the relationship between parents and children. For each person, we hold a list of their children in order of birth. A separate set keeps track of dead members (to exclude them during the inheritance order retrieval). The getInheritanceOrder function performs a depth-first traversal (preorder) starting from the king. During the traversal, we add each living member to the result list and recursively traverse their children in order.