1554. Minimum Time to Collect All Apples in a Tree
My accepted C++ solution to LeetCode problem 1554, Minimum Time to Collect All Apples in a Tree, running in 43ms.
- Difficulty: Medium
- C++
- Runtime 43ms
- Memory 65.5MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 43ms, memory 65.5MB, accepted 2025-12-27.
class Solution {
public:
int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
vector<vector<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
return dfs(0, -1, adj, hasApple);
}
int dfs(int node, int parent, vector<vector<int>>& adj, vector<bool>& hasApple) {
int totalTime = 0;
for (int child : adj[node]) {
if (child == parent) continue;
int childTime = dfs(child, node, adj, hasApple);
if (childTime > 0 || hasApple[child]) {
totalTime += childTime + 2;
}
}
return totalTime;
}
};