Amount of Time for Binary Tree to Be Infected

medium

Given the root of a binary tree and the value start of an initially infected node, each minute an infected node spreads the infection to all its adjacent nodes — left child, right child, and parent. Return the number of minutes needed for the entire tree to become infected.

All node values are unique and start exists in the tree. The tree is given in level-order (breadth-first), using null for missing children.

Hints

The infection spreads to children and the parent, so treat the tree as an undirected graph.
The answer is the distance from start to the farthest node.
Add parent pointers and BFS from start, counting levels — or combine up-distance and down-height in one DFS.

Common doubts

Infection spreads one edge per minute in all directions, so the last node infected is the farthest one, at distance equal to that maximum.
The infection also moves upward to the parent, which a rooted binary tree can't express without recording parents (or handling it in the DFS).
It returns a negative depth for the subtree containing start, so an ancestor can add that distance to the opposite subtree's height.

Interview follow-ups

Both root the tree as a graph and spread from a start node; here you want the maximum distance rather than the nodes at an exact distance.
The eccentricity of the start node — its greatest distance to any other node.

Fun facts

  • The answer is exactly the start node's eccentricity in the tree viewed as a graph.
  • The signed-DFS trick — negative depth means 'contains the special node' — recurs in many one-pass tree solutions.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 5, 3, null, 4, 10, 6, 9, 2], start = 3
Output: 4
The infection reaches the farthest nodes (9 and 2) after 4 minutes.
Example 2
Input: root = [1], start = 1
Output: 0
The only node is already infected, so no time is needed.
Constraints

- The number of nodes is in the range [1, 10^5] - 1 <= Node.val <= 10^5 - All Node.val are unique - The start value exists in the tree

Solve this problem →