1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
throne-inheritance.py 1.16 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 5年前 . Create throne-inheritance.py
# Time: ctor: O(1)
# birth: O(1)
# death: O(1)
# inherit: O(n)
# Space: O(n)
import collections
class ThroneInheritance(object):
def __init__(self, kingName):
"""
:type kingName: str
"""
self.__king = kingName
self.__family_tree = collections.defaultdict(list)
self.__dead = set()
def birth(self, parentName, childName):
"""
:type parentName: str
:type childName: str
:rtype: None
"""
self.__family_tree[parentName].append(childName)
def death(self, name):
"""
:type name: str
:rtype: None
"""
self.__dead.add(name)
def getInheritanceOrder(self):
"""
:rtype: List[str]
"""
result = []
stk = [self.__king]
while stk: # preorder traversal
node = stk.pop()
if node not in self.__dead:
result.append(node)
if node not in self.__family_tree:
continue
for child in reversed(self.__family_tree[node]):
stk.append(child)
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助