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:
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:
[1, 105].1 <= Node.val <= 105start exists in the tree.Approach 1: Breadth-First Search (BFS)
This approach involves simulating the infection spread using BFS, starting from the infected node. Each level of the BFS traversal represents one minute of infection spreading.
The steps are as follows:
This C solution creates a graph-like structure from the binary tree and performs a breadth-first search from the start node to determine the infection spread time.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N) where N is the number of nodes; we visit each node once.
Space Complexity: O(N) to store the adjacency list and manage the queue.
Approach 2: Depth-First Search with Backtracking
In this method, we perform a depth-first search (DFS) to calculate the maximum distance (time) required to infect every node from the start node, utilizing backtracking to manage node revisits.
Steps include:
This C solution deploys a DFS strategy to recursively compute time taken to infect each node, storing the maximum time found.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N)
Space Complexity: O(N) for the recursion stack if the tree is unbalanced.
| Approach | Complexity |
|---|---|
| Approach 1: Breadth-First Search | Time Complexity: O(N) where N is the number of nodes; we visit each node once. |
| Approach 2: Depth-First Search with Backtracking | Time Complexity: O(N) |
L31. Minimum time taken to BURN the Binary Tree from a Node | C++ | Java • take U forward • 179,723 views views
Watch 9 more video solutions →Practice Amount of Time for Binary Tree to Be Infected with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor