forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
40 lines (35 loc) · 1 KB
/
Solution.ts
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
class ThroneInheritance {
private king: string;
private dead: Set<string> = new Set();
private g: Map<string, string[]> = new Map();
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[] {
const ans: string[] = [];
const dfs = (x: string) => {
if (!this.dead.has(x)) {
ans.push(x);
}
for (const y of this.g.get(x) || []) {
dfs(y);
}
};
dfs(this.king);
return ans;
}
}
/**
* 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()
*/