File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: ctor: O(1)
2
+ // birth: O(1)
3
+ // death: O(1)
4
+ // inherit: O(n)
5
+ // Space: O(n)
6
+
7
+ class ThroneInheritance {
8
+ public:
9
+ ThroneInheritance (string kingName) : king_name_(kingName) {
10
+
11
+ }
12
+
13
+ void birth (string parentName, string childName) {
14
+ family_tree_[parentName].emplace_back (childName);
15
+ }
16
+
17
+ void death (string name) {
18
+ dead_.emplace (name);
19
+ }
20
+
21
+ vector<string> getInheritanceOrder () {
22
+ vector<string> result;
23
+ vector<string> stk = {king_name_};
24
+ while (!empty (stk)) { // preorder traversal
25
+ const auto node = move (stk.back ()); stk.pop_back ();
26
+ if (!dead_.count (node)) {
27
+ result.emplace_back (node);
28
+ }
29
+ if (!family_tree_.count (node)) {
30
+ continue ;
31
+ }
32
+ for (int i = size (family_tree_[node]) - 1 ; i >= 0 ; --i) {
33
+ stk.emplace_back (family_tree_[node][i]);
34
+ }
35
+ }
36
+ return result;
37
+ }
38
+
39
+ private:
40
+ string king_name_;
41
+ unordered_map<string, vector<string>> family_tree_;
42
+ unordered_set<string> dead_;
43
+ };
You can’t perform that action at this time.
0 commit comments