forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
41 lines (35 loc) · 1.04 KB
/
Solution.java
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
class ThroneInheritance {
private String king;
private Set<String> dead = new HashSet<>();
private Map<String, List<String>> g = new HashMap<>();
private List<String> ans = new ArrayList<>();
public ThroneInheritance(String kingName) {
king = kingName;
}
public void birth(String parentName, String childName) {
g.computeIfAbsent(parentName, k -> new ArrayList<>()).add(childName);
}
public void death(String name) {
dead.add(name);
}
public List<String> getInheritanceOrder() {
ans.clear();
dfs(king);
return ans;
}
private void dfs(String x) {
if (!dead.contains(x)) {
ans.add(x);
}
for (String y : 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();
*/