1
+ # Runtime: 1338 ms (Top 35.29%) | Memory: 68.8 MB (Top 82.35%)
2
+
1
3
class ThroneInheritance :
2
4
3
5
def __init__ (self , kingName : str ):
@@ -7,14 +9,14 @@ def __init__(self, kingName: str):
7
9
# notDead will hold all the people who are alive and their level number
8
10
self .alive = {}
9
11
self .alive [kingName ] = 0
10
-
12
+
11
13
# hold edges existing in our graph
12
14
self .edges = {self .root :[]}
13
-
15
+
14
16
def birth (self , parentName : str , childName : str ) -> None :
15
17
# birth --> new child so update alive
16
18
self .alive [childName ] = self .alive [parentName ]+ 1
17
-
19
+
18
20
# add parent to child edges in the edges dictionary
19
21
if parentName in self .edges :
20
22
self .edges [parentName ].append (childName )
@@ -24,25 +26,24 @@ def birth(self, parentName: str, childName: str) -> None:
24
26
if childName not in self .edges :
25
27
self .edges [childName ] = []
26
28
self .edges [parentName ] = [childName ]
27
-
28
-
29
+
29
30
def death (self , name : str ) -> None :
30
31
# removing the dead people from alive map
31
32
del self .alive [name ]
32
-
33
+
33
34
def getInheritanceOrder (self ) -> List [str ]:
34
-
35
+
35
36
hierarchy = []
36
37
def dfs (cur ,parent = - 1 ):
37
38
nonlocal hierarchy
38
-
39
+
39
40
# current person available in alive then only add in hierarchy
40
41
if cur in self .alive :
41
42
hierarchy .append (cur )
42
-
43
+
43
44
# traverse all the children of current node
44
45
for i in self .edges [cur ]:
45
46
if i != parent :
46
47
dfs (i ,cur )
47
48
dfs (self .root )
48
- return hierarchy
49
+ return hierarchy
0 commit comments