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: From Node 3153410692STARTMinute 0: Node 3 infectedMinute 1: Nodes 1,10,6 infectedMinute 2: Node 5 infectedMinute 3: Node 4 infectedMinute 4: Nodes 9,2 infectedTotal Infection Time: 4 minutes
Understanding the Visualization
1
Initial State
Tree with infection starting at specified node
2
Spread Process
Infection spreads to adjacent nodes each minute
3
Complete Infection
Time when last node becomes infected
Key Takeaway
🎯 Key Insight: Convert the tree to a graph and use BFS to simulate infection spread level by level
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