forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations-on-tree.py
64 lines (59 loc) · 1.53 KB
/
operations-on-tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Time: ctor: O(n)
# lock: O(1)
# unlock: O(1)
# upgrade: O(n)
# Space: O(n)
class LockingTree(object):
def __init__(self, parent):
"""
:type parent: List[int]
"""
self.__parent = parent
self.__children = [[] for _ in xrange(len(parent))]
for i, x in enumerate(parent):
if x != -1:
self.__children[x].append(i)
self.__locked = {}
def lock(self, num, user):
"""
:type num: int
:type user: int
:rtype: bool
"""
if num in self.__locked:
return False
self.__locked[num] = user
return True
def unlock(self, num, user):
"""
:type num: int
:type user: int
:rtype: bool
"""
if self.__locked.get(num) != user:
return False
del self.__locked[num]
return True
def upgrade(self, num, user):
"""
:type num: int
:type user: int
:rtype: bool
"""
node = num
while node != -1:
if node in self.__locked:
return False
node = self.__parent[node]
result = False
stk = [num]
while stk:
node = stk.pop()
if node in self.__locked:
del self.__locked[node]
result = True
for child in self.__children[node]:
stk.append(child)
if result:
self.__locked[num] = user
return result