Talentd
FleetCode

2385. Amount of Time for Binary Tree to Be Infected

Medium65.8% acceptance12 companies

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.

Example 1:

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.

Example 2:

Input: root = [1], start = 1
Output: 0
Explanation: At minute 0, the only node in the tree is infected so we return 0.

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 start exists in the tree.

Hints open one at a time

Hint 1
Convert the tree to an undirected graph to make it easier to handle.
Hint 2
Use BFS starting at the start node to find the distance between each node and the start node. The answer is the maximum distance.
29:25
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class Solution:
8 def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
9
Starter codePython 3Spaces: 4
Examples
Input
[1,5,3,null,4,10,6,9,2]
3
Input
[1]
1
Your code is saved on this device.Solution