LeetCode 2385: Amount of Time for Binary Tree to Be Infected
Problem Description
Explanation
To solve this problem, we can perform a breadth-first search starting from the initially infected node. We can keep track of the nodes that are infected at each minute and increment the minute count until all nodes are infected. We will use a queue to keep track of the nodes to be processed at each minute.
Algorithm:
- Initialize a queue to store the currently infected nodes.
- Add the initially infected node to the queue.
- Initialize a minute counter to 0.
- While the queue is not empty, do the following:
- Increment the minute counter.
- Create a new queue to store the nodes that will get infected in the next minute.
- For each node in the current queue:
- Mark the node as infected.
- Iterate over the adjacent nodes of the current node:
- If the adjacent node is uninfected, mark it as infected and add it to the new queue.
- Update the current queue with the new queue.
The time complexity of this approach is O(N), where N is the number of nodes in the binary tree. The space complexity is also O(N) in the worst case.
Solutions
class Solution {
public int minTimeToInfect(TreeNode root, int start) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
Set<TreeNode> infected = new HashSet<>();
infected.add(root);
int minutes = 0;
while (!queue.isEmpty()) {
minutes++;
Queue<TreeNode> nextLevel = new LinkedList<>();
for (TreeNode node : queue) {
for (TreeNode neighbor : getNeighbors(node)) {
if (!infected.contains(neighbor)) {
infected.add(neighbor);
nextLevel.offer(neighbor);
}
}
}
queue = nextLevel;
}
return minutes - 1;
}
private List<TreeNode> getNeighbors(TreeNode node) {
List<TreeNode> neighbors = new ArrayList<>();
if (node.left != null) neighbors.add(node.left);
if (node.right != null) neighbors.add(node.right);
return neighbors;
}
}
Loading editor...