Minimum Time to Collect All Apples in a Tree - Problem
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree.
Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.
Input & Output
Example 1 — Basic Tree
$
Input:
n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
›
Output:
8
💡 Note:
Start at 0. Go to node 2 (2 seconds), collect apple at node 2, then go to node 3 (2 seconds), return to 2 (2 seconds), then return to 0 (2 seconds). Total: 8 seconds.
Example 2 — Single Apple
$
Input:
n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
›
Output:
0
💡 Note:
No apples to collect, so no need to move from starting position. Total: 0 seconds.
Example 3 — All Apples
$
Input:
n = 4, edges = [[0,1],[1,2],[0,3]], hasApple = [true,true,true,true]
›
Output:
6
💡 Note:
Must visit all nodes: 0→1→2 (return to 1, then 0), then 0→3 (return to 0). Path: 0→1→2→1→0→3→0. Total: 6 seconds.
Constraints
- 1 ≤ n ≤ 105
- edges.length == n - 1
- edges[i].length == 2
- 0 ≤ ai, bi ≤ n - 1
- ai ≠ bi
- hasApple.length == n
Visualization
Tap to expand
Understanding the Visualization
1
Tree Structure
Build adjacency list from edges array
2
DFS Traversal
Use DFS to check which subtrees have apples
3
Optimal Path
Only visit branches that contain apples
Key Takeaway
🎯 Key Insight: Only traverse subtrees containing apples using DFS, avoiding unnecessary branches
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code