难度:中等
思路:
- 首先为了更好的访问每个节点的子节点,我们创建一个字典来表示key节点下的所有子节点,其次上锁,解锁不用多说
- 升级过程,对于条件一和三可以理解为同一个,即包括它本身在内的所有祖先节点都未上锁
- 对于条件二,递归遍历所有的子孙节点,如果有已上锁状态的则改为未上锁状态并返回True
class LockingTree:
def __init__(self, parent: List[int]):
self.parent = parent
self.child = defaultdict(list)
for c, p in enumerate(self.parent):
self.child[p].append(c)
self.locked = [-1] * len(parent)
def lock(self, num: int, user: int) -> bool:
if self.locked[num] == -1:
self.locked[num] = user
return True
return False
def unlock(self, num: int, user: int) -> bool:
if self.locked[num] == user:
self.locked[num] = -1
return True
return False
def upgrade(self, num: int, user: int) -> bool:
n = num
while n != -1:
if self.locked[n] != -1:
return False
n = self.parent[n]
def find(root):
t = False
for i in self.child[root]:
if self.locked[i] != -1:
self.locked[i] = -1
t = True
if find(i):
t = True
return t
if find(num):
self.locked[num] = user
return True
return False