Amount of Time for Binary Tree to Be Infected - Problem
Imagine a viral infection spreading through a binary tree! You are given the root of a binary tree where each node has a unique value, and an integer start representing the initial infection point.
At minute 0, the infection begins at the node with value start. Each subsequent minute, the infection spreads to all adjacent uninfected nodes. In a binary tree, adjacent nodes are:
- Parent and child nodes
- Child and parent nodes
Your task is to determine the total number of minutes needed for the infection to spread to every single node in the tree.
Goal: Return the minimum time required for complete tree infection.
Input & Output
example_1.py โ Basic Tree Infection
$
Input:
root = [1,5,3,null,4,10,6,9,2], start = 3
โบ
Output:
4
๐ก Note:
Starting from node 3, infection spreads: Minute 0: {3}, Minute 1: {1,10,6}, Minute 2: {5,2}, Minute 3: {4}, Minute 4: {9}. Total time: 4 minutes.
example_2.py โ Simple Chain
$
Input:
root = [1], start = 1
โบ
Output:
0
๐ก Note:
Single node tree - infection starts and completes immediately at minute 0.
example_3.py โ Linear Tree
$
Input:
root = [1,2,null,3,null,4,null], start = 3
โบ
Output:
2
๐ก Note:
Linear tree: 1โ2โ3โ4. Starting from 3, it takes 2 minutes to reach nodes 1 and 4 (the furthest nodes).
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Infection starts at the specified start node (minute 0)
2
First Spread
Infection spreads to all directly connected nodes (minute 1)
3
Continued Spread
Each minute, infection spreads to next level of uninfected neighbors
4
Complete Infection
All nodes infected - return total minutes elapsed
Key Takeaway
๐ฏ Key Insight: The problem is essentially finding the longest path from the start node in an undirected version of the tree. Converting the tree to a graph or using clever DFS allows us to handle bidirectional infection spread efficiently.
Time & Space Complexity
Time Complexity
O(n)
Single DFS traversal visits each node exactly once
โ Linear Growth
Space Complexity
O(h)
Recursion stack space proportional to tree height h
โ Linear Space
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 value
startexists in the tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code