-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem024.go
66 lines (61 loc) · 1.42 KB
/
problem024.go
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
package problem024
type binaryTree struct {
lockedDescendantsCount int
locked bool
parent *binaryTree
left *binaryTree
right *binaryTree
}
func NewBinaryTree(left *binaryTree, right *binaryTree) *binaryTree {
node := binaryTree{
parent: nil,
lockedDescendantsCount: 0,
locked: false,
left: left,
right: right,
}
if right != nil {
right.parent = &node
}
if left != nil {
left.parent = &node
}
return &node
}
func (node *binaryTree) IsLocked() bool {
return node.locked
}
func (node *binaryTree) Lock() bool {
if node.lockedDescendantsCount > 0 {
return false
}
ascendants := make([]*binaryTree, 0, 64)
for cursor := node.parent; cursor != nil; cursor = cursor.parent {
if cursor.locked {
return false
}
ascendants = append(ascendants, cursor)
}
for _, ascendant := range ascendants {
ascendant.lockedDescendantsCount++
}
node.locked = true
return true
}
func (node *binaryTree) Unlock() bool {
if node.lockedDescendantsCount > 0 {
return false
}
ascendants := make([]*binaryTree, 0, 64)
for cursor := node.parent; cursor != nil; cursor = cursor.parent {
if cursor.locked {
return false
}
ascendants = append(ascendants, cursor)
}
for _, ascendant := range ascendants {
ascendant.lockedDescendantsCount--
}
node.locked = false
return true
}