-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirusKiller.java
More file actions
34 lines (27 loc) · 913 Bytes
/
VirusKiller.java
File metadata and controls
34 lines (27 loc) · 913 Bytes
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
package Trees;
public class VirusKiller {
private int maxDistance = 0;
public int amountOfTime(Node root, int start) {
traverse(root, start);
return maxDistance;
}
public int traverse(Node root, int start) {
int depth = 0;
if (root == null) {
return depth;
}
int leftDepth = traverse(root.left, start);
int rightDepth = traverse(root.right, start);
if (root.val == start) {
maxDistance = Math.max(leftDepth, rightDepth);
depth = -1;
} else if (leftDepth >= 0 && rightDepth >= 0) {
depth = Math.max(leftDepth, rightDepth) + 1;
} else {
int distance = Math.abs(leftDepth) + Math.abs(rightDepth);
maxDistance = Math.max(maxDistance, distance);
depth = Math.min(leftDepth, rightDepth) - 1;
}
return depth;
}
}