Skip to content

Commit c9e2566

Browse files
authored
Create throne-inheritance.py
1 parent 8d87a65 commit c9e2566

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Python/throne-inheritance.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Time: ctor: O(1)
2+
# birth: O(1)
3+
# death: O(1)
4+
# inherit: O(n)
5+
# Space: O(n)
6+
7+
import collections
8+
9+
10+
class ThroneInheritance(object):
11+
12+
def __init__(self, kingName):
13+
"""
14+
:type kingName: str
15+
"""
16+
self.__king = kingName
17+
self.__family_tree = collections.defaultdict(list)
18+
self.__dead = set()
19+
20+
21+
def birth(self, parentName, childName):
22+
"""
23+
:type parentName: str
24+
:type childName: str
25+
:rtype: None
26+
"""
27+
self.__family_tree[parentName].append(childName)
28+
29+
30+
def death(self, name):
31+
"""
32+
:type name: str
33+
:rtype: None
34+
"""
35+
self.__dead.add(name)
36+
37+
38+
def getInheritanceOrder(self):
39+
"""
40+
:rtype: List[str]
41+
"""
42+
result = []
43+
stk = [self.__king]
44+
while stk: # preorder traversal
45+
node = stk.pop()
46+
if node not in self.__dead:
47+
result.append(node)
48+
if node not in self.__family_tree:
49+
continue
50+
for child in reversed(self.__family_tree[node]):
51+
stk.append(child)
52+
return result
53+

0 commit comments

Comments
 (0)