Amount of Time for Binary Tree to Be Infected (LeetCode 2385): Solution and Explanation
An infection starts at the node with value start and spreads each minute to every healthy parent or child of an infected node. Return how many minutes it takes for the whole tree to be infected.
Intuition
The infection moves along tree edges in both directions, up to parents as well as down to children. A tree node has no parent pointer, so the natural move is to rebuild the tree as an undirected graph first.
Once it is a graph, each minute is one BFS layer. The node infected last is the node farthest from start, so the answer is the number of layers after the first, which is the largest distance from start.
Approach: Tree to undirected graph, then layered BFS
- Walk the tree with a stack. For every parent-child pair, add each value to the other's adjacency list.
- Start BFS with
frontier = [start],seen = {start}, andminutes = -1. - While the frontier is not empty, increase
minutesand build the next frontier from every unseen neighbour of the current one. - When the frontier becomes empty,
minutesis the minute of the last infection. Return it.
Step-by-step example
root = [1,5,3,null,4,10,6,9,2], start = 3
- Build the graph: 1-5, 1-3, 5-4, 3-10, 3-6, 4-9, 4-2, each in both directions.
- Minute 0: node 3 is infected.
- Minute 1: its neighbours 1, 10 and 6 catch it. Node 1 is the parent, which is why the graph needs upward edges.
- Minute 2: node 5. Minute 3: node 4. Minute 4: nodes 9 and 2.
- The next frontier is empty, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
3 graph = collections.defaultdict(list)
4 stack = [root]
5 while stack:
6 node = stack.pop()
7 for child in (node.left, node.right):
8 if child:
9 graph[node.val].append(child.val)
10 graph[child.val].append(node.val)
11 stack.append(child)
12 seen = {start}
13 frontier = [start]
14 minutes = -1
15 while frontier:
16 minutes += 1
17 nxt = []
18 for v in frontier:
19 for u in graph[v]:
20 if u not in seen:
21 seen.add(u)
22 nxt.append(u)
23 frontier = nxt
24 return minutes1class Solution {
2 public int amountOfTime(TreeNode root, int start) {
3 Map<Integer, List<Integer>> graph = new HashMap<>();
4 Deque<TreeNode> stack = new ArrayDeque<>();
5 stack.push(root);
6 while (!stack.isEmpty()) {
7 TreeNode node = stack.pop();
8 for (TreeNode child : new TreeNode[] {node.left, node.right}) {
9 if (child == null) continue;
10 graph.computeIfAbsent(node.val, k -> new ArrayList<>()).add(child.val);
11 graph.computeIfAbsent(child.val, k -> new ArrayList<>()).add(node.val);
12 stack.push(child);
13 }
14 }
15 Set<Integer> seen = new HashSet<>();
16 seen.add(start);
17 List<Integer> frontier = new ArrayList<>();
18 frontier.add(start);
19 int minutes = -1;
20 while (!frontier.isEmpty()) {
21 minutes++;
22 List<Integer> next = new ArrayList<>();
23 for (int v : frontier) {
24 for (int u : graph.getOrDefault(v, Collections.emptyList())) {
25 if (seen.add(u)) {
26 next.add(u);
27 }
28 }
29 }
30 frontier = next;
31 }
32 return minutes;
33 }
34}1class Solution {
2public:
3 int amountOfTime(TreeNode* root, int start) {
4 unordered_map<int, vector<int>> graph;
5 vector<TreeNode*> stack = {root};
6 while (!stack.empty()) {
7 TreeNode* node = stack.back();
8 stack.pop_back();
9 for (TreeNode* child : {node->left, node->right}) {
10 if (!child) continue;
11 graph[node->val].push_back(child->val);
12 graph[child->val].push_back(node->val);
13 stack.push_back(child);
14 }
15 }
16 unordered_set<int> seen = {start};
17 vector<int> frontier = {start};
18 int minutes = -1;
19 while (!frontier.empty()) {
20 minutes++;
21 vector<int> next;
22 for (int v : frontier) {
23 for (int u : graph[v]) {
24 if (seen.insert(u).second) {
25 next.push_back(u);
26 }
27 }
28 }
29 frontier = next;
30 }
31 return minutes;
32 }
33};Time and space complexity
O(n)
Building the graph touches every edge once, and BFS visits every node and edge once.
O(n)
The adjacency list stores 2(n - 1) entries, and the seen set and frontier hold up to n values.
Other approaches
Single DFS with depth bookkeeping (time O(n), space O(h))
One post-order DFS returns each subtree's height, and when the walk finds start it returns its distance upward. At each ancestor, the farthest node through the other side is distance to start plus the other subtree's height. Track the maximum. No graph is built.
Parent map instead of adjacency list (time O(n), space O(n))
Record only each node's parent in a hash map, find the start node, then BFS over left, right and parent pointers. Same complexity, slightly less memory than a full adjacency list.
Common mistakes
- Only spreading downward. Start may be deep in the tree, and the farthest node is often on the other side of the root.
- Returning the number of BFS layers instead of layers minus one. Minute 0 is the start itself.
- Forgetting the seen set, so the infection walks back to its parent and loops forever.
- Assuming start is the root and returning the tree height.
Frequently asked questions
Why does the answer equal the largest distance from start?
Each minute the infection advances exactly one edge in every direction, so a node at distance d is infected at minute d. The whole tree is infected when the farthest node is.
What if the tree has one node?
Start is the only node, it is infected at minute 0, and nothing else needs to happen, so the answer is 0.
Can I avoid building the graph?
Yes. A single DFS can combine subtree heights with the distance from each ancestor to start, which needs only O(h) space. The graph version is easier to get right.