-
Notifications
You must be signed in to change notification settings - Fork 0
/
dailycoding024.py
71 lines (56 loc) · 1.91 KB
/
dailycoding024.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
65
66
67
68
69
70
71
class LockTreeNode:
def __init__(self, val, left=None, right=None, parent=None):
self.left = left
self.right = right
self.parent = parent
self.val = val
self.is_locked = False
self.num_locked_children = 0
def _can_lock_or_unlock(self):
if self.num_locked_children > 0:
return False
# Traverse all the parent nodes to check is_locked
curr = self.parent
while curr:
if curr.is_locked:
return False
curr = curr.parent
return True
def is_locked(self):
return self.is_locked
def lock(self):
if self._can_lock_or_unlock():
# locking is successful
self.is_locked = True
curr = self.parent
while curr:
curr.num_locked_children += 1
curr = curr.parent
return True
else:
return False
def unlock(self):
if self._can_lock_or_unlock():
# Unlock the node
self.is_locked = False
curr = self.parent
while curr:
curr.num_locked_children -= 1
curr = curr.parent
return True
else:
return False
def main():
root = LockTreeNode(100)
root.left = LockTreeNode(200, parent=root)
root.right = LockTreeNode(5, parent=root)
root.left.left = LockTreeNode(300, parent=root.left)
root.left.right = LockTreeNode(150, parent=root.left)
root.left.right.left = LockTreeNode(170, parent=root.left.right)
root.left.right.right = LockTreeNode(130, parent=root.left.right)
root.left.right.lock()
print(f"Locking a locked branch: {root.left.right.right.lock()}")
print(f"Unlocking locked node: {root.left.right.unlock()}")
print(f"Locking after unlock: {root.left.right.right.lock()}")
if __name__ == '__main__':
main()