Leetcode #2385: Amount of Time for Binary Tree to Be Infected
In this guide, we solve Leetcode #2385 Amount of Time for Binary Tree to Be Infected in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Output: 4
Explanation: The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
def dfs(node: Optional[TreeNode], fa: Optional[TreeNode]):
if node is None:
return
if fa:
g[node.val].append(fa.val)
g[fa.val].append(node.val)
dfs(node.left, node)
dfs(node.right, node)
def dfs2(node: int, fa: int) -> int:
ans = 0
for nxt in g[node]:
if nxt != fa:
ans = max(ans, 1 + dfs2(nxt, node))
return ans
g = defaultdict(list)
dfs(root, None)
return dfs2(start, -1)
Complexity
The time complexity is , and the space complexity is , where is the number of nodes in the binary tree. The space complexity is , where is the number of nodes in the binary tree.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.