-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_024.js
87 lines (79 loc) Β· 1.95 KB
/
problem_024.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Node {
/**
* Initialize a binary tree node with a value and/or left and right nodes
* @param {*} val The value stored in the binary tree node.
*/
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
// Additional node info
this.isLocked = false;
this.parent = null;
this.lockedChildCount = 0;
}
}
/**
* Return whether the node is locked
* @param {Node} node
* @return {boolean}
*/
const isLocked = (node) => {
return node.isLocked;
}
/**
* Checks to see if we can lock or unlock this node by checking ancestors and descendants
* @param {Node} node
* @return {boolean}
*/
const canLockOrUnlock = (node) => {
if (node.lockedChildCount > 0) return false;
// Check descendant isLocked for parent nodes
let curr = node.parent;
while (curr !== null) {
if (curr.isLocked) return false;
curr = curr.parent;
}
return true;
}
/**
* Tries to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true.
* @param {Node} node
* @return {boolean}
*/
const lock = (node) => {
if (node === null) return false;
if (!node.isLocked && canLockOrUnlock(node)) {
node.isLocked = true;
// Update count in all ancestors
let curr = node.parent;
while (curr !== null) {
curr.lockedChildCount += 1;
curr = curr.parent;
}
return true;
}
return false;
}
/**
* Unlocks the node.
* If it cannot be unlocked, then it should return false.
* Otherwise, it should unlock it and return true.
* @param {Node} node
* @return {boolean}
*/
const unlock = (node) => {
if (node === null) return false;
if (node.isLocked && canLockOrUnlock(node)) {
node.isLocked = false;
// Update count in all ancestors
let curr = node.parent;
let curr = node.parent;
while (curr !== null) {
curr.lockedChildCount -= 1;
curr = curr.parent;
}
return true;
}
return false;
}