2385. Amount of Time for Binary Tree to Be Infected

DFS + BFS

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
class Solution {
public int amountOfTime(TreeNode root, int start) {
Map<Integer, List<Integer>> nodeToNodeListMap = new HashMap<>();
dfs(nodeToNodeListMap, root);

int minutes = -1;

Set<Integer> visitedNodeSet = new HashSet<>();
visitedNodeSet.add(start);
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
while (!queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
int node = queue.poll();
List<Integer> toList = nodeToNodeListMap.get(node);
if (toList != null) {
for (int to : toList) {
if (visitedNodeSet.contains(to)) {
continue;
}
queue.offer(to);
visitedNodeSet.add(to);
}
}
}

minutes++;
}

return minutes;
}

private void dfs(Map<Integer, List<Integer>> nodeToNodeListMap, TreeNode root) {
if (root.left != null) {
int from = root.val, to = root.left.val;
nodeToNodeListMap.computeIfAbsent(from, key -> new ArrayList<>()).add(to);
nodeToNodeListMap.computeIfAbsent(to, key -> new ArrayList<>()).add(from);
dfs(nodeToNodeListMap, root.left);
}
if (root.right != null) {
int from = root.val, to = root.right.val;
nodeToNodeListMap.computeIfAbsent(from, key -> new ArrayList<>()).add(to);
nodeToNodeListMap.computeIfAbsent(to, key -> new ArrayList<>()).add(from);
dfs(nodeToNodeListMap, root.right);
}
}
}

DFS

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
class Solution {
private static class State {
private Integer startDepth;
private int minutes;
}

public int amountOfTime(TreeNode root, int start) {
State state = new State();
dfs(state, root, 0, start);
return state.minutes;
}

private int dfs(State state, TreeNode root, int depth, int start) {
if (root == null) {
return 0;
}
if (root.val == start) {
state.startDepth = depth;
}

int leftDepth = dfs(state, root.left, depth + 1, start);
boolean startInLeftTree = state.startDepth != null;
int rightDepth = dfs(state, root.right, depth + 1, start);
boolean startInRightTree = !startInLeftTree && state.startDepth != null;

if (root.val == start) {
state.minutes = Math.max(state.minutes, Math.max(leftDepth, rightDepth));
} else if (startInLeftTree) {
state.minutes = Math.max(state.minutes, state.startDepth - depth + rightDepth);
} else if (startInRightTree) {
state.minutes = Math.max(state.minutes, state.startDepth - depth + leftDepth);
}

return Math.max(leftDepth, rightDepth) + 1;
}
}

此解法需画图加深理解。

References

2385. Amount of Time for Binary Tree to Be Infected