Similar Problems
Similar Problems not available
Minimum Time To Collect All Apples In A Tree  Leetcode Solution
Companies:
LeetCode: Minimum Time To Collect All Apples In A Tree Leetcode Solution
Difficulty: Medium
Topics: hashtable tree depthfirstsearch breadthfirstsearch
Problem Statement:
Given a tree in which each vertex represents a fruitbearing apple tree, you need to collect all the apples without skipping your instructions.
The apple tree is represented by an integer array where the value of the ith element is the location of the ith apple tree. You can start at any vertex of the tree and visit each vertex in any order.
You can collect apples at any vertex as long as you’ve reached the equipment that’s installed there.
Return the minimum time in seconds you need to collect all apples in the tree starting at vertex 0.
Solution:
The problem statement asks us to find the minimum time required to collect all apples in the tree. We can solve this problem using the Breadth First Search algorithm.
We start from the root node (node 0) and traverse the tree to collect the apples. We maintain a variable called distance, which represents the distance traveled so far, and a boolean array called visited, which represents whether a particular node has been visited or not.
We use a priority queue that stores the next node that we should visit based on the distance, with the minimum distance always on top.
During the traversal, we check if the current node has an apple tree. If yes, we mark it as visited and add the distance to the total distance.
We continue the traversal until we visit all the nodes with apple trees and return the total distance traveled.
Algorithm:

Initialize distance = 0 and visited[0] = true.

Create a priority queue pq and push the root node 0 with distance 0.

While pq is not empty:
a. Pop the node with minimum distance.
b. If node i has an apple tree and has not been visited yet, add the distance to the total distance and mark visited[i] as true.
c. For each neighbor j of node i:
i. If the neighbor j has not been visited yet, push it to pq with the distance traveled so far plus the distance between i and j.

Return the total distance traveled.
Time Complexity: O(nlogn), where n is the number of nodes in the tree.
Space Complexity: O(n), where n is the number of nodes in the tree.
Implementation:
Here’s the implementation of the above algorithm in Python:
import heapq
class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) > int: visited = [False] * n distance = 0 graph = [[] for _ in range(n)]
for i in range(len(edges)):
u, v = edges[i]
graph[u].append(v)
graph[v].append(u)
pq = [(0, 0)]
visited[0] = True
while pq:
dist, node = heapq.heappop(pq)
if hasApple[node] and not visited[node]:
visited[node] = True
distance += dist
for neighbor in graph[node]:
if not visited[neighbor]:
heapq.heappush(pq, (dist + 1, neighbor))
return distance * 2
Minimum Time To Collect All Apples In A Tree Solution Code
1