Leetcode 2385: Amount of Time for Binary Tree to Be Infected

grid47
grid47
Exploring patterns and algorithms
Mar 13, 2024 7 min read

You are given the root of a binary tree where each node has a unique value, and an integer start representing the initial infected node. At minute 0, the infection begins at the node with value start. Each minute, an adjacent uninfected node becomes infected. Your task is to return the total number of minutes it takes for the entire tree to become infected.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary tree represented by the root node and an integer start.
Example: Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Constraints:
• 1 <= The number of nodes in the tree <= 10^5
• 1 <= Node.val <= 10^5
• Each node has a unique value.
• A node with the value 'start' exists in the tree.
Output: Return the number of minutes it will take for the entire tree to be infected.
Example: Output: 4
Constraints:
Goal: The goal is to calculate the time required for the entire tree to be infected by spreading the infection level by level.
Steps:
• 1. Convert the binary tree into an undirected graph where each node is connected to its adjacent nodes.
• 2. Perform a breadth-first search (BFS) starting from the infected node (start).
• 3. For each level of BFS, increment the time (minute).
• 4. Continue the process until all nodes are infected.
Goal: Consider constraints related to the size of the tree and the structure of the graph.
Steps:
• The tree will have up to 10^5 nodes.
• Each node has a unique value.
Assumptions:
• The infection spreads to adjacent nodes every minute, and no node is re-infected.
Input: Input: root = [1,5,3,null,4,10,6,9,2], start = 3
Explanation: At minute 0, the infection starts at node 3. At each subsequent minute, neighboring nodes become infected. It takes 4 minutes for all nodes to be infected, hence the output is 4.

Input: Input: root = [1], start = 1
Explanation: In this case, there is only one node in the tree, and it's infected at minute 0, so no time is needed for the entire tree to be infected. The output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus