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
Minimum Time to Collect All Apples in a Tree INPUT 0 1 2 4 5 3 6 Has Apple No Apple n = 7 hasApple: [F,F,T,F,T,T,F] Start at vertex 0 ALGORITHM STEPS 1 DFS from Root Start at node 0, traverse all children recursively 2 Check Subtrees For each child, check if subtree contains apples 3 Prune Empty Paths Skip branches with no apples (nodes 3, 6) 4 Sum Edge Costs Add 2 for each edge on path (go + return) Visited Paths: 0-->1-->4 (2+2=4) 0-->1-->5 (2+2=4) 0-->2 (2) Edge 0-1 counted once! FINAL RESULT 0 1 2 4 5 3 6 Edge Count: 0-1: 2 sec | 1-4: 2 sec 1-5: 2 sec | 0-2: 2 sec Output: 8 seconds OK - All apples collected! Key Insight: Use DFS to explore all paths from root. Only traverse edges that lead to subtrees containing apples. Each required edge is traversed twice (once going, once returning). Prune branches without apples to minimize time. Time = 2 * (number of edges on paths to apple nodes). Here: 4 edges x 2 = 8 seconds. TutorialsPoint - Minimum Time to Collect All Apples in a Tree | DFS with Apple-aware Pruning
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
89.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen