1993. 树上的操作
# 1993. 树上的操作 (opens new window)
# 1.哈希
难点在于update实现,需要遍历当前节点的祖先节点和子树。其中祖先节点直接根据parent数组遍历;子树则需要建立哈希表保存节点的孩子节点,递归map的子节点。
class LockingTree {
private static class Node{
int userId;
int parentId;
boolean lock;
}
Node[] tree;
Map<Integer,List<Integer>> map;
public LockingTree(int[] parent) {
map=new HashMap<>();
tree=new Node[parent.length];
for(int i=0;i<parent.length;i++){
tree[i]=new Node();
tree[i].parentId=parent[i];
if(map.containsKey(parent[i])){
map.get(parent[i]).add(i);
}
else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(parent[i], list);
}
}
}
public boolean lock(int num, int user) {
if(!tree[num].lock){
tree[num].lock=true;
tree[num].userId=user;
return true;
}
else{
return false;
}
}
public boolean unlock(int num, int user) {
if(tree[num].lock&&tree[num].userId==user){
tree[num].lock=false;
return true;
}
else return false;
}
public boolean upgrade(int num, int user) {
int father=tree[num].parentId;
boolean checkFather=false;
while(father!=-1){
if(tree[father].lock){
checkFather=true;
break;
}
father=tree[father].parentId;
}
boolean checkSon=map.containsKey(num)?check(num):false;
if(checkFather||tree[num].lock||!checkSon) return false;
release(num);
tree[num].userId=user;
tree[num].lock=true;
return true;
}
public boolean check(int num){
for(Integer i:map.get(num)){
if(tree[i].lock)return true;
if(map.containsKey(i)&&check(i)) return true;
}
return false;
}
public void release(int num){
for(Integer i:map.get(num)){
tree[i].lock=false;
if(map.containsKey(i)) release(i);
}
}
}
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
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
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57