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
startexists in the tree.
Visualization
Tap to expand
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code