Amount of Time for Binary Tree to Be Infected - Solution & Explanation
Problem Statement
You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.
Each minute, a node becomes infected if:
- The node is currently uninfected.
- The node is adjacent to an infected node.
Return the number of minutes needed for the entire tree to be infected.
Example 1:
Input: root = [1,5,3,null,4,10,6,9,2], start = 3 Output: 4 Explanation: The following nodes are infected during: - Minute 0: Node 3 - Minute 1: Nodes 1, 10 and 6 - Minute 2: Node 5 - Minute 3: Node 4 - Minute 4: Nodes 9 and 2 It takes 4 minutes for the whole tree to be infected so we return 4.
Example 2:
Input: root = [1], start = 1 Output: 0 Explanation: At minute 0, the only node in the tree is infected so we return 0.
Constraints:
- The number of nodes in the tree is in the range
[1, 105]. 1 <= Node.val <= 105- Each node has a unique value.
- A node with a value of
startexists in the tree.
Approach Overview
Problem Overview: A virus starts spreading from a specific node in a binary tree. Each minute, the infection spreads to the nodeβs parent and children. The task is to compute how many minutes it takes until every node in the tree becomes infected.
Approach 1: Breadth-First Search (Graph Conversion) (Time: O(n), Space: O(n))
The tree structure only gives you child pointers. Infection spreads in three directions: left child, right child, and parent. Because parent references are missing, first convert the tree into an undirected graph using a hash table (adjacency list). Traverse the tree once and connect each node with its parent and children.
After building the graph, start a breadth-first search from the start node. BFS naturally models the infection process because each level of traversal represents one minute. Push the start node into a queue, expand to all unvisited neighbors, and count how many layers are processed. The final BFS depth equals the total infection time. This approach is straightforward and mirrors multi-source spreading problems such as rotting oranges.
Approach 2: Depth-First Search with Backtracking (Time: O(n), Space: O(n))
This approach avoids explicitly building a graph. Instead, perform a recursive depth-first search on the binary tree. The idea is to locate the start node and then propagate distances upward while simultaneously computing the farthest infection distance in subtrees.
During DFS, return the distance from the current node to the start node. When the start node is found, compute the height of its left and right subtrees to determine infection spread downward. When recursion unwinds, use the returned distance to infect the opposite subtree through the parent path. Each step updates the global maximum infection time.
This technique effectively simulates infection traveling both downward and upward in the tree. The recursion carries two pieces of information: distance to the start node and subtree heights. Although slightly harder to reason about than BFS, it avoids building an explicit adjacency structure.
Recommended for interviews: The BFS graph approach is usually the expected answer. Converting the tree into an undirected graph and running BFS clearly models the infection spreading minute by minute. It demonstrates strong understanding of tree traversal and graph traversal patterns. The DFS backtracking solution is elegant and optimal as well, but interviewers often prefer the BFS reasoning because it is easier to explain and debug.
Approach 1: Approach 1: Breadth-First Search
Approach 1: Breadth-First Search (BFS)
This approach involves simulating the infection spread using BFS, starting from the infected node. Each level of the BFS traversal represents one minute of infection spreading.
The steps are as follows:
- Convert the binary tree into a graph represented using an adjacency list. Since each node can infect its parent, left child, and right child, we need to treat the tree as a graph to easily find adjacent nodes.
- Use a BFS to traverse and track the infection spread, starting from the node with the 'start' value. Each time we move to the next level in our BFS, it represents the infection spreading to more nodes, thus increasing the time by one minute.
- Keep track of visited nodes to avoid processing the same node multiple times.
- The depth or number of levels needed to reach all nodes will be the time required to infect the entire tree.
This C solution creates a graph-like structure from the binary tree and performs a breadth-first search from the start node to determine the infection spread time.
Complexity
Time Complexity: O(N) where N is the number of nodes; we visit each node once.
Space Complexity: O(N) to store the adjacency list and manage the queue.
Approach 2: Approach 2: Depth-First Search with Backtracking
Approach 2: Depth-First Search with Backtracking
In this method, we perform a depth-first search (DFS) to calculate the maximum distance (time) required to infect every node from the start node, utilizing backtracking to manage node revisits.
Steps include:
- Use DFS to traverse and mark nodes as visited, calculating the time taken to spread infection to each node recursively.
- Track maximum infection time encountered as we explore different paths.
- This approach is especially useful in trees where we may want to calculate distribution paths directly instead of simulating BFS.
This C solution deploys a DFS strategy to recursively compute time taken to infect each node, storing the maximum time found.
Complexity
Time Complexity: O(N)
Space Complexity: O(N) for the recursion stack if the tree is unbalanced.
Approach 3: Two DFS
First, we build a graph through one DFS, and get an adjacency list g, where g[node] represents all nodes connected to the node node.
Then, we use start as the starting point, and search the entire tree through DFS to find the farthest distance, which is the answer.
The time complexity is O(n), and the space complexity is O(n), where n is the number of nodes in the binary tree.
Code
Python
Java
C++
Go
TypeScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Breadth-First Search | Time Complexity: O(N) where N is the number of nodes; we visit each node once. |
| Approach 2: Depth-First Search with Backtracking | Time Complexity: O(N) |
| Two DFS | β |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Breadth-First Search (Graph Conversion) | O(n) | O(n) | Best general solution. Easy to reason about infection spread level by level. |
| Depth-First Search with Backtracking | O(n) | O(n) | Useful when you want to avoid building an explicit graph and compute distances during recursion. |
Video Solution
Amount of Time for Binary Tree to Be Infected | Using BFS | Leetcode 2385 β’ codestorywithMIK β’ 13,767 views views
Watch 9 more video solutions βFrequently Asked Questions
Is Amount of Time for Binary Tree to Be Infected easy or hard?
Amount of Time for Binary Tree to Be Infected Python/Java solution
How to solve Amount of Time for Binary Tree to Be Infected in O(n)?
What is the best approach for Amount of Time for Binary Tree to Be Infected?
Is Amount of Time for Binary Tree to Be Infected asked at Google/Amazon/Meta?
What data structure is used in Amount of Time for Binary Tree to Be Infected?
What is the time complexity of Amount of Time for Binary Tree to Be Infected?
Ready to solve this problem?
Practice Amount of Time for Binary Tree to Be Infected with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor