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
Infection Spread TimelineMinute 0316Minute 1316Minute 231652๐Ÿ”ฅ Red: Initially infected, ๐ŸŸก Orange: Infected this minute, ๐ŸŸข Green: Just infected
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

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack space proportional to tree height h

n
2n
โœ“ 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 start exists in the tree
Asked in
Meta 45 Amazon 38 Google 32 Microsoft 28
52.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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