forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
66 lines (61 loc) · 1.27 KB
/
Solution.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
type LockingTree struct {
nums map[int]int
parent []int
children [][]int
}
func Constructor(parent []int) LockingTree {
n := len(parent)
nums := make(map[int]int)
children := make([][]int, n)
for i, p := range parent {
if p != -1 {
children[p] = append(children[p], i)
}
}
return LockingTree{nums, parent, children}
}
func (this *LockingTree) Lock(num int, user int) bool {
if _, ok := this.nums[num]; ok {
return false
}
this.nums[num] = user
return true
}
func (this *LockingTree) Unlock(num int, user int) bool {
if this.nums[num] != user {
return false
}
delete(this.nums, num)
return true
}
func (this *LockingTree) Upgrade(num int, user int) bool {
for t := num; t != -1; t = this.parent[t] {
if _, ok := this.nums[t]; ok {
return false
}
}
find := false
var dfs func(int)
dfs = func(num int) {
for _, child := range this.children[num] {
if _, ok := this.nums[child]; ok {
delete(this.nums, child)
find = true
}
dfs(child)
}
}
dfs(num)
if !find {
return false
}
this.nums[num] = user
return true
}
/**
* Your LockingTree object will be instantiated and called as such:
* obj := Constructor(parent);
* param_1 := obj.Lock(num,user);
* param_2 := obj.Unlock(num,user);
* param_3 := obj.Upgrade(num,user);
*/