-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththroneInheritance.cpp
More file actions
45 lines (38 loc) · 1.09 KB
/
throneInheritance.cpp
File metadata and controls
45 lines (38 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Source: https://leetcode.com/problems/throne-inheritance/
// Author: Miao Zhang
// Date: 2021-05-19
class ThroneInheritance {
public:
ThroneInheritance(string kingName) : king_(kingName) {
}
void birth(string parentName, string childName) {
order_[parentName].push_back(childName);
}
void death(string name) {
dead_.insert(name);
}
vector<string> getInheritanceOrder() {
vector<string> res;
function<void(string)> dfs = [&] (string king) {
if (!dead_.count(king)) {
res.push_back(king);
}
for (auto child: order_[king]) {
dfs(child);
}
};
dfs(king_);
return res;
}
private:
string king_;
unordered_map<string, vector<string>> order_;
unordered_set<string> dead_;
};
/**
* 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();
*/