Member-only story
Leetcode 1443: Minimum Time to Collect All Apples in a Tree
2 min readMay 20, 2020
In this Leetcode problem, we are to return the minimum number of steps to pickup all the apples in an undirected tree, starting from the node 0
.
Solution
Here is the draft of ideas to solve the problem recursively:
- Let’s call
visit(p)
the cost to visit the subtree with rootp
. For instance, in the above example,visit(1)
is6
,visit(4)
is 2. - Let’s call
neighbors(p)
the children ofp
in the rooted representation of the tree (root is0
) - To calculate
visit(p)
, start recursively to computevisit(i)
for alli
inneighbors(p)
, and retain the sum insum
- if
sum
is not0
, thenvisit(p) = 2 + sum
, we add to for the cost to com from and to the parent ofp
- if
sum
is0
, then ifp
has an apple return2
, otherwise return0
- At the top level,
0
, the cost of 2 to come from and to the parent doesn’t exists, because0
doesn’t have a parent, so it should be removed at the end
Here is the full Java code corresponding to the solution:
class Solution {
public int minTime(
int n, int[][] edges, List<Boolean> hasApple) {
Set<Integer> visited = new HashSet<>();
Map<Integer, Set<Integer>> adjacency = new…