> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Time to Collect All Apples in a Tree

> Tested Python solution for LeetCode 1443 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 1443, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), DP on Trees. [View on LeetCode](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1443   # by problem number
lcpy gen -s minimum_time_to_collect_all_apples_in_a_tree   # by problem name
```

## 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] = [a<sub>i</sub>, b<sub>i</sub>]` means that exists an edge connecting the vertices `a<sub>i</sub>` and `b<sub>i</sub>`. 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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png)

```
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](https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png)

```
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.
```

```
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 \<= 10^5
* edges.length == n - 1
* edges\[i].length == 2
* 0 \<= a\<sub>i\</sub> \< b\<sub>i\</sub> \<= n - 1
* hasApple.length == n

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_time_to_collect_all_apples_in_a_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_time_to_collect_all_apples_in_a_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def min_time(self, n: int, edges: list[list[int]], has_apple: list[bool]) -> int:
        adj: list[list[int]] = [[] for _ in range(n)]
        for a, b in edges:
            adj[a].append(b)
            adj[b].append(a)

        seen = [False] * n
        parent = [-1] * n
        order = [0]
        seen[0] = True
        for u in order:
            for v in adj[u]:
                if not seen[v]:
                    seen[v] = True
                    parent[v] = u
                    order.append(v)

        subtree_has_apple = list(has_apple)
        total = 0
        for u in reversed(order):
            if u == 0:
                continue
            if subtree_has_apple[u]:
                total += 2
                subtree_has_apple[parent[u]] = True
        return total
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.