Skip to content

Commit 0171fe9

Browse files
authored
Create operations-on-tree.py
1 parent 405ace0 commit 0171fe9

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Python/operations-on-tree.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Time: ctor: O(n)
2+
# lock: O(1)
3+
# unlock: O(1)
4+
# upgrade: O(n)
5+
# Space: O(n)
6+
7+
class LockingTree(object):
8+
9+
def __init__(self, parent):
10+
"""
11+
:type parent: List[int]
12+
"""
13+
self.__parent = parent
14+
self.__children = [[] for _ in xrange(len(parent))]
15+
for i, x in enumerate(parent):
16+
if x != -1:
17+
self.__children[x].append(i)
18+
self.__locked = {}
19+
20+
def lock(self, num, user):
21+
"""
22+
:type num: int
23+
:type user: int
24+
:rtype: bool
25+
"""
26+
if num in self.__locked:
27+
return False
28+
self.__locked[num] = user
29+
return True
30+
31+
def unlock(self, num, user):
32+
"""
33+
:type num: int
34+
:type user: int
35+
:rtype: bool
36+
"""
37+
if self.__locked.get(num) != user:
38+
return False
39+
del self.__locked[num]
40+
return True
41+
42+
def upgrade(self, num, user):
43+
"""
44+
:type num: int
45+
:type user: int
46+
:rtype: bool
47+
"""
48+
node = num
49+
while node != -1:
50+
if node in self.__locked:
51+
return False
52+
node = self.__parent[node]
53+
result = False
54+
stk = [num]
55+
while stk:
56+
node = stk.pop()
57+
if node in self.__locked:
58+
del self.__locked[node]
59+
result = True
60+
for child in self.__children[node]:
61+
stk.append(child)
62+
if result:
63+
self.__locked[num] = user
64+
return result

0 commit comments

Comments
 (0)