Watch 10 video solutions for Minimum Time to Collect All Apples in a Tree, a medium level problem involving Hash Table, Tree, Depth-First Search. This walkthrough by NeetCodeIO has 25,321 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Example 1:
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 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] Output: 6 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 3:
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
Constraints:
1 <= n <= 105edges.length == n - 1edges[i].length == 20 <= ai < bi <= n - 1hasApple.length == nProblem Overview: You are given an undirected tree with n nodes where some nodes contain apples. Starting from node 0, you must collect every apple and return to the root. Each edge traversal costs 1 second. The goal is to compute the minimum time needed to visit all apple nodes and return.
Approach 1: DFS Traversal with Backtracking (O(n) time, O(n) space)
The tree structure naturally fits a depth-first traversal. Build an adjacency list for the graph, then run DFS from node 0. Each recursive call explores child nodes while skipping the parent to avoid revisiting edges. The key insight: only add traversal cost if a subtree contains an apple. If a child subtree returns a positive cost or the child node itself has an apple, you add 2 seconds to account for traveling to that child and returning. Otherwise, skip that branch entirely. This selective accumulation ensures you only traverse edges that lead to apples. DFS works well because it aggregates information bottom‑up: each subtree reports whether collecting apples below it required travel.
This approach relies heavily on tree traversal and recursive aggregation, a common pattern in problems involving subtree properties. You process each node once, so time complexity stays linear.
Approach 2: BFS Alternative Strategy (O(n) time, O(n) space)
A breadth-first strategy can solve the problem by first building parent relationships from the root using BFS. After constructing the parent map, iterate through all nodes that contain apples and trace the path back to the root. Mark edges that must be used to reach these apples. A set or boolean structure tracks visited edges so shared paths are counted only once. Each unique edge required for collecting apples contributes 2 seconds because you travel down and back along that edge.
This method uses breadth-first search for tree exploration and leverages parent pointers to reconstruct paths efficiently. Compared to DFS, it separates graph traversal from cost calculation. The logic is sometimes easier to visualize but requires additional structures to track visited edges.
Recommended for interviews: DFS with backtracking is the expected solution. Interviewers want to see you recognize that the graph is a tree and that only subtrees containing apples should contribute to the traversal cost. The bottom‑up aggregation pattern is common in depth-first search tree problems. BFS works but adds unnecessary bookkeeping, while DFS expresses the logic more directly.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| DFS Traversal with Backtracking | O(n) | O(n) | Best general solution for tree problems where subtree information determines whether edges should be included |
| BFS with Parent Path Reconstruction | O(n) | O(n) | Useful when parent relationships or level-order traversal are already required |