Skip to content

Commit 7cd268f

Browse files
authored
Create 1600-throne-inheritance.js
1 parent b53835f commit 7cd268f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1600-throne-inheritance.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {string} kingName
3+
*/
4+
const ThroneInheritance = function(kingName) {
5+
this.king = kingName
6+
this.m = {}
7+
this.dead = {}
8+
};
9+
10+
/**
11+
* @param {string} parentName
12+
* @param {string} childName
13+
* @return {void}
14+
*/
15+
ThroneInheritance.prototype.birth = function(parentName, childName) {
16+
if(!this.m[parentName]) this.m[parentName] = []
17+
this.m[parentName].push(childName)
18+
};
19+
20+
/**
21+
* @param {string} name
22+
* @return {void}
23+
*/
24+
ThroneInheritance.prototype.death = function(name) {
25+
this.dead[name] = 1
26+
};
27+
28+
/**
29+
* @return {string[]}
30+
*/
31+
ThroneInheritance.prototype.getInheritanceOrder = function() {
32+
const res = []
33+
this.dfs(res, this.king)
34+
return res
35+
};
36+
ThroneInheritance.prototype.dfs = function(ans, root) {
37+
if (!this.dead[root]) {
38+
ans.push(root);
39+
}
40+
if(!this.m[root]) return
41+
for (let child of this.m[root]) {
42+
this.dfs(ans, child);
43+
}
44+
};
45+
/**
46+
* Your ThroneInheritance object will be instantiated and called as such:
47+
* var obj = new ThroneInheritance(kingName)
48+
* obj.birth(parentName,childName)
49+
* obj.death(name)
50+
* var param_3 = obj.getInheritanceOrder()
51+
*/

0 commit comments

Comments
 (0)