forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
46 lines (40 loc) · 1.22 KB
/
Solution.cs
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
46
public class ThroneInheritance {
private string king;
private HashSet<string> dead = new HashSet<string>();
private Dictionary<string, List<string>> g = new Dictionary<string, List<string>>();
private List<string> ans = new List<string>();
public ThroneInheritance(string kingName) {
king = kingName;
}
public void Birth(string parentName, string childName) {
if (!g.ContainsKey(parentName)) {
g[parentName] = new List<string>();
}
g[parentName].Add(childName);
}
public void Death(string name) {
dead.Add(name);
}
public IList<string> GetInheritanceOrder() {
ans.Clear();
DFS(king);
return ans;
}
private void DFS(string x) {
if (!dead.Contains(x)) {
ans.Add(x);
}
if (g.ContainsKey(x)) {
foreach (string y in 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);
* IList<string> param_3 = obj.GetInheritanceOrder();
*/