-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 172.java
More file actions
75 lines (56 loc) · 2.17 KB
/
Day 172.java
File metadata and controls
75 lines (56 loc) · 2.17 KB
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
import java.util.*;
class Solution {
public int minTime(Node root, int target) {
Map<Node, Node> parentMap = new HashMap<>();
Node targetNode = mapParents(root, parentMap, target);
Queue<Node> queue = new LinkedList<>();
Set<Node> visited = new HashSet<>();
queue.offer(targetNode);
visited.add(targetNode);
int time = 0;
while (!queue.isEmpty()) {
int size = queue.size();
boolean burned = false;
for (int i = 0; i < size; i++) {
Node curr = queue.poll();
if (curr.left != null && !visited.contains(curr.left)) {
queue.offer(curr.left);
visited.add(curr.left);
burned = true;
}
if (curr.right != null && !visited.contains(curr.right)) {
queue.offer(curr.right);
visited.add(curr.right);
burned = true;
}
if (parentMap.containsKey(curr) && !visited.contains(parentMap.get(curr))) {
queue.offer(parentMap.get(curr));
visited.add(parentMap.get(curr));
burned = true;
}
}
if (burned) time++;
}
return time;
}
private Node mapParents(Node root, Map<Node, Node> parentMap, int target) {
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
Node targetNode = null;
while (!queue.isEmpty()) {
Node curr = queue.poll();
if (curr.data == target) {
targetNode = curr;
}
if (curr.left != null) {
parentMap.put(curr.left, curr);
queue.offer(curr.left);
}
if (curr.right != null) {
parentMap.put(curr.right, curr);
queue.offer(curr.right);
}
}
return targetNode;
}
}