#1443
Minimum Time to Collect All Apples in a Tree
MediumHash TableTreeDepth-First SearchBreadth-First SearchDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses Depth-First Search (DFS) to traverse the tree and only counts the time for edges that lead to apples. This avoids unnecessary traversal and efficiently calculates the minimum time.
⚙️
Algorithm
3 steps- 1Step 1: Build a graph representation of the tree using adjacency lists.
- 2Step 2: Use DFS to traverse the tree, starting from the root.
- 3Step 3: For each node, check if it or any of its descendants have apples; if so, add the time to traverse that edge (2 seconds for round trip).
solution.py14 lines
1def minTime(n, edges, hasApple):
2 graph = {i: [] for i in range(n)}
3 for u, v in edges:
4 graph[u].append(v)
5 graph[v].append(u)
6 def dfs(node, parent):
7 total_time = 0
8 for neighbor in graph[node]:
9 if neighbor != parent:
10 time = dfs(neighbor, node)
11 if time > 0 or hasApple[neighbor]:
12 total_time += time + 2
13 return total_time
14 return dfs(0, -1)ℹ
Complexity note: This complexity arises because we visit each node exactly once during the DFS traversal, making it linear with respect to the number of nodes.
- 1Only traverse paths that lead to apples to minimize time.
- 2A depth-first search is effective for tree structures.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.