A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
In the beginning, curOrder will be ["king"].
Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].
Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].
Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].
Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"].
Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:
ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.
void birth(string parentName, string childName) Indicates that parentName gave birth to childName.
void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.
string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.
Example 1:
Input
["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]]
Output
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
Explanation
ThroneInheritance t= new ThroneInheritance("king"); // order: king
t.birth("king", "andy"); // order: king > andy
t.birth("king", "bob"); // order: king > andy > bob
t.birth("king", "catherine"); // order: king > andy > bob > catherine
t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
kingName, parentName, childName, and name consist of lowercase English letters only.
All arguments childName and kingName are distinct.
All name arguments of death will be passed to either the constructor or as childName to birth first.
For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
At most 105 calls will be made to birth and death.
At most 10 calls will be made to getInheritanceOrder.
Solutions
Solution 1: Preorder Traversal of a Multi-branch Tree
Thinking
The given \(\textit{Successor}\) walks to the oldest child not yet listed, then backtracks to the parent. Simulating that definition on every query rescans children lists; with up to \(10^5\) births the family can be large enough that each query becomes quadratic.
The same recurrence is a preorder walk of a multi-way tree: output the person, then recurse on children in birth order. Death does not reshape the tree — it only omits a name from the final list — so it suffices to store adjacency lists and a death set.
A hash table \(g\) records children in insertion order and a set \(\textit{dead}\) marks deaths. Birth and death are amortized \(O(1)\); \(\texttt{getInheritanceOrder}\) DFS from the king and appends living nodes in preorder.
According to the problem description, we can find that the order of throne inheritance is actually a preorder traversal of a multi-branch tree. We can use a hash table \(g\) to store the children of each person, and a set \(\textit{dead}\) to store the people who have died.
When calling birth(parentName, childName), we add childName to the child list of parentName.
When calling death(name), we add name to the \(\textit{dead}\) set.
When calling getInheritanceOrder(), we start a depth-first search from the king. If the current node x is not dead, we add x to the answer list, and then recursively traverse all children of x.
In terms of time complexity, both \(\textit{birth}\) and \(\textit{death}\) have a time complexity of \(O(1)\), and \(\textit{getInheritanceOrder}\) has a time complexity of \(O(n)\). The space complexity is \(O(n)\), where \(n\) is the number of nodes.
classThroneInheritance:def__init__(self,kingName:str):self.king=kingNameself.dead=set()self.g=defaultdict(list)defbirth(self,parentName:str,childName:str)->None:self.g[parentName].append(childName)defdeath(self,name:str)->None:self.dead.add(name)defgetInheritanceOrder(self)->list[str]:defdfs(x:str):xnotinself.deadandans.append(x)foryinself.g[x]:dfs(y)ans=[]dfs(self.king)returnans# Your ThroneInheritance object will be instantiated and called as such:# obj = ThroneInheritance(kingName)# obj.birth(parentName,childName)# obj.death(name)# param_3 = obj.getInheritanceOrder()
classThroneInheritance{privateStringking;privateSet<String>dead=newHashSet<>();privateMap<String,List<String>>g=newHashMap<>();privateList<String>ans=newArrayList<>();publicThroneInheritance(StringkingName){king=kingName;}publicvoidbirth(StringparentName,StringchildName){g.computeIfAbsent(parentName,k->newArrayList<>()).add(childName);}publicvoiddeath(Stringname){dead.add(name);}publicList<String>getInheritanceOrder(){ans.clear();dfs(king);returnans;}privatevoiddfs(Stringx){if(!dead.contains(x)){ans.add(x);}for(Stringy:g.getOrDefault(x,List.of())){dfs(y);}}}/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance obj = new ThroneInheritance(kingName); * obj.birth(parentName,childName); * obj.death(name); * List<String> param_3 = obj.getInheritanceOrder(); */
classThroneInheritance{public:ThroneInheritance(stringkingName){king=kingName;}voidbirth(stringparentName,stringchildName){g[parentName].emplace_back(childName);}voiddeath(stringname){dead.insert(name);}vector<string>getInheritanceOrder(){ans.resize(0);dfs(king);returnans;}private:stringking;unordered_set<string>dead;unordered_map<string,vector<string>>g;vector<string>ans;voiddfs(string&x){if(!dead.contains(x)){ans.emplace_back(x);}for(auto&y:g[x]){dfs(y);}}};/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance* obj = new ThroneInheritance(kingName); * obj->birth(parentName,childName); * obj->death(name); * vector<string> param_3 = obj->getInheritanceOrder(); */
typeThroneInheritancestruct{kingstringdeadmap[string]boolgmap[string][]string}funcConstructor(kingNamestring)ThroneInheritance{returnThroneInheritance{kingName,map[string]bool{},map[string][]string{}}}func(this*ThroneInheritance)Birth(parentNamestring,childNamestring){this.g[parentName]=append(this.g[parentName],childName)}func(this*ThroneInheritance)Death(namestring){this.dead[name]=true}func(this*ThroneInheritance)GetInheritanceOrder()(ans[]string){vardfsfunc(string)dfs=func(xstring){if!this.dead[x]{ans=append(ans,x)}for_,y:=rangethis.g[x]{dfs(y)}}dfs(this.king)return}/** * Your ThroneInheritance object will be instantiated and called as such: * obj := Constructor(kingName); * obj.Birth(parentName,childName); * obj.Death(name); * param_3 := obj.GetInheritanceOrder(); */
classThroneInheritance{privateking:string;privatedead:Set<string>=newSet();privateg:Map<string,string[]>=newMap();constructor(kingName:string){this.king=kingName;}birth(parentName:string,childName:string):void{this.g.set(parentName,this.g.get(parentName)||[]);this.g.get(parentName)!.push(childName);}death(name:string):void{this.dead.add(name);}getInheritanceOrder():string[]{constans:string[]=[];constdfs=(x:string)=>{if(!this.dead.has(x)){ans.push(x);}for(constyofthis.g.get(x)||[]){dfs(y);}};dfs(this.king);returnans;}}/** * Your ThroneInheritance object will be instantiated and called as such: * var obj = new ThroneInheritance(kingName) * obj.birth(parentName,childName) * obj.death(name) * var param_3 = obj.getInheritanceOrder() */
publicclassThroneInheritance{privatestringking;privateHashSet<string>dead=newHashSet<string>();privateDictionary<string,List<string>>g=newDictionary<string,List<string>>();privateList<string>ans=newList<string>();publicThroneInheritance(stringkingName){king=kingName;}publicvoidBirth(stringparentName,stringchildName){if(!g.ContainsKey(parentName)){g[parentName]=newList<string>();}g[parentName].Add(childName);}publicvoidDeath(stringname){dead.Add(name);}publicIList<string>GetInheritanceOrder(){ans.Clear();DFS(king);returnans;}privatevoidDFS(stringx){if(!dead.Contains(x)){ans.Add(x);}if(g.ContainsKey(x)){foreach(stringying[x]){DFS(y);}}}}/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance obj = new ThroneInheritance(kingName); * obj.Birth(parentName,childName); * obj.Death(name); * IList<string> param_3 = obj.GetInheritanceOrder(); */
Solution 2: Explicit-Stack Preorder
Thinking
The given \(\textit{Successor}\) walks to the oldest child not yet listed, then backtracks to the parent. Simulating that definition on every query rescans children and becomes quadratic once the number of births reaches \(10^5\). The same recurrence is a preorder walk of a multi-way tree: write the person, then visit children in birth order. Death does not reshape the tree; it only omits a name. Recursion along a birth chain uses a call depth equal to the family size and overflows Python once the chain reaches length \(1000\). The query therefore uses a stack. A popped person is appended when still alive, and that person's children are pushed from last to first so the oldest child is popped next.
The inheritance order is a preorder traversal of a multi-way tree. A hash table \(g\) stores each person's children in birth order, and a set \(\textit{dead}\) stores the people who have died.
When calling birth(parentName, childName), append childName to the child list of parentName.
When calling death(name), add name to \(\textit{dead}\).
When calling getInheritanceOrder(), the stack starts with the king. After x is popped, append x when x is not in \(\textit{dead}\), then push the children of x from last to first so birth order is preserved.
In terms of time complexity, both \(\textit{birth}\) and \(\textit{death}\) have a time complexity of \(O(1)\), and \(\textit{getInheritanceOrder}\) has a time complexity of \(O(n)\). The space complexity is \(O(n)\), where \(n\) is the number of nodes.
classThroneInheritance:def__init__(self,kingName:str):self.king=kingNameself.dead=set()self.g=defaultdict(list)defbirth(self,parentName:str,childName:str)->None:self.g[parentName].append(childName)defdeath(self,name:str)->None:self.dead.add(name)defgetInheritanceOrder(self)->list[str]:ans=[]stk=[self.king]whilestk:x=stk.pop()ifxnotinself.dead:ans.append(x)foryinreversed(self.g[x]):stk.append(y)returnans# Your ThroneInheritance object will be instantiated and called as such:# obj = ThroneInheritance(kingName)# obj.birth(parentName,childName)# obj.death(name)# param_3 = obj.getInheritanceOrder()
classThroneInheritance{privateStringking;privateSet<String>dead=newHashSet<>();privateMap<String,List<String>>g=newHashMap<>();publicThroneInheritance(StringkingName){king=kingName;}publicvoidbirth(StringparentName,StringchildName){g.computeIfAbsent(parentName,k->newArrayList<>()).add(childName);}publicvoiddeath(Stringname){dead.add(name);}publicList<String>getInheritanceOrder(){List<String>ans=newArrayList<>();Deque<String>stk=newArrayDeque<>();stk.push(king);while(!stk.isEmpty()){Stringx=stk.pop();if(!dead.contains(x)){ans.add(x);}List<String>children=g.getOrDefault(x,List.of());for(inti=children.size()-1;i>=0;--i){stk.push(children.get(i));}}returnans;}}/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance obj = new ThroneInheritance(kingName); * obj.birth(parentName,childName); * obj.death(name); * List<String> param_3 = obj.getInheritanceOrder(); */
classThroneInheritance{public:ThroneInheritance(stringkingName){king=kingName;}voidbirth(stringparentName,stringchildName){g[parentName].emplace_back(childName);}voiddeath(stringname){dead.insert(name);}vector<string>getInheritanceOrder(){vector<string>ans;vector<string>stk{king};while(!stk.empty()){stringx=stk.back();stk.pop_back();if(!dead.contains(x)){ans.emplace_back(x);}autoit=g.find(x);if(it==g.end()){continue;}auto&children=it->second;for(inti=(int)children.size()-1;i>=0;--i){stk.push_back(children[i]);}}returnans;}private:stringking;unordered_set<string>dead;unordered_map<string,vector<string>>g;};/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance* obj = new ThroneInheritance(kingName); * obj->birth(parentName,childName); * obj->death(name); * vector<string> param_3 = obj->getInheritanceOrder(); */
typeThroneInheritancestruct{kingstringdeadmap[string]boolgmap[string][]string}funcConstructor(kingNamestring)ThroneInheritance{returnThroneInheritance{kingName,map[string]bool{},map[string][]string{}}}func(this*ThroneInheritance)Birth(parentNamestring,childNamestring){this.g[parentName]=append(this.g[parentName],childName)}func(this*ThroneInheritance)Death(namestring){this.dead[name]=true}func(this*ThroneInheritance)GetInheritanceOrder()(ans[]string){stk:=[]string{this.king}forlen(stk)>0{x:=stk[len(stk)-1]stk=stk[:len(stk)-1]if!this.dead[x]{ans=append(ans,x)}children:=this.g[x]fori:=len(children)-1;i>=0;i--{stk=append(stk,children[i])}}return}/** * Your ThroneInheritance object will be instantiated and called as such: * obj := Constructor(kingName); * obj.Birth(parentName,childName); * obj.Death(name); * param_3 := obj.GetInheritanceOrder(); */
classThroneInheritance{privateking:string;privatedead:Set<string>=newSet();privateg:Map<string,string[]>=newMap();constructor(kingName:string){this.king=kingName;}birth(parentName:string,childName:string):void{this.g.set(parentName,this.g.get(parentName)||[]);this.g.get(parentName)!.push(childName);}death(name:string):void{this.dead.add(name);}getInheritanceOrder():string[]{constans:string[]=[];conststk:string[]=[this.king];while(stk.length){constx=stk.pop()!;if(!this.dead.has(x)){ans.push(x);}constchildren=this.g.get(x)||[];for(leti=children.length-1;i>=0;--i){stk.push(children[i]);}}returnans;}}/** * Your ThroneInheritance object will be instantiated and called as such: * var obj = new ThroneInheritance(kingName) * obj.birth(parentName,childName) * obj.death(name) * var param_3 = obj.getInheritanceOrder() */
publicclassThroneInheritance{privatestringking;privateHashSet<string>dead=newHashSet<string>();privateDictionary<string,List<string>>g=newDictionary<string,List<string>>();publicThroneInheritance(stringkingName){king=kingName;}publicvoidBirth(stringparentName,stringchildName){if(!g.ContainsKey(parentName)){g[parentName]=newList<string>();}g[parentName].Add(childName);}publicvoidDeath(stringname){dead.Add(name);}publicIList<string>GetInheritanceOrder(){List<string>ans=newList<string>();Stack<string>stk=newStack<string>();stk.Push(king);while(stk.Count>0){stringx=stk.Pop();if(!dead.Contains(x)){ans.Add(x);}if(g.ContainsKey(x)){List<string>children=g[x];for(inti=children.Count-1;i>=0;--i){stk.Push(children[i]);}}}returnans;}}/** * Your ThroneInheritance object will be instantiated and called as such: * ThroneInheritance obj = new ThroneInheritance(kingName); * obj.Birth(parentName,childName); * obj.Death(name); * IList<string> param_3 = obj.GetInheritanceOrder(); */