Amount of Time for Binary Tree to Be Infected - Problem

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.

Input & Output

Example 1 — Basic Tree Infection
$ Input: root = [1,5,3,null,4,10,6,null,null,9,2], start = 3
Output: 4
💡 Note: At minute 0, node 3 is infected. At minute 1, nodes 1 and 10 and 6 become infected. At minute 2, node 5 becomes infected. At minute 3, node 4 becomes infected. At minute 4, nodes 9 and 2 become infected. Total time: 4 minutes.
Example 2 — Single Node
$ Input: root = [1], start = 1
Output: 0
💡 Note: Only one node in the tree, so it takes 0 minutes to infect the entire tree.
Example 3 — Start from Leaf
$ Input: root = [1,2,3,4,5], start = 4
Output: 3
💡 Note: Starting from leaf node 4, it takes 3 minutes to reach the farthest node on the other side of the tree.

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 start exists in the tree.

Visualization

Tap to expand
Binary Tree Infection Spread INPUT 1 5 3 4 10 6 9 2 root = [1,5,3,null,4,10,6, null,null,9,2] start = 3 (Red node = infection start) ALGORITHM (BFS) 1 Build Graph Convert tree to undirected adjacency list 2 Initialize BFS Queue = [start], visited = {3} time = 0 3 Spread Level by Level Process all nodes at current level, add neighbors to queue 4 Track Minutes Increment time after each level until queue empty Infection Timeline: t=0: [3] t=1: [1, 10, 6] t=2: [5, 9, 2] t=3: [4] t=4: [] (all infected) FINAL RESULT 1 5 3 4 10 6 9 2 All nodes infected! Output: 4 4 minutes to infect entire tree - OK Key Insight: Convert the binary tree to an undirected graph (adjacency list) so infection can spread in all directions. BFS from the start node naturally processes nodes level by level - each level represents one minute. The answer is the maximum distance (in edges) from start to any other node = tree diameter from start. TutorialsPoint - Amount of Time for Binary Tree to Be Infected | BFS Approach Time Complexity: O(n) | Space Complexity: O(n)
Asked in
Facebook 35 Amazon 28 Microsoft 22 Google 18
32.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen