---
# System prepended metadata

title: 1443. Minimum Time to Collect All Apples in a Tree
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 1443. Minimum Time to Collect All Apples in a Tree

###### Link : https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/

## 題目
最短路徑找到所有蘋果
## 程式碼

```cpp=
class Solution {
public:
    int DFS(int node, int parent, vector<vector<int>>& adj, vector<bool>& hasApple){
        int childtime = 0, totaltime = 0;
        for(auto& child:adj[node]){
            if(child == parent)
                continue;
            childtime = DFS(child, node, adj, hasApple);
            if(childtime || hasApple[child]) totaltime += childtime + 2;
        }
        return totaltime;
    }
    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
        vector<vector<int>> adj(n);
        for(auto& edge : edges){
            adj[edge[0]].push_back(edge[1]);
            adj[edge[1]].push_back(edge[0]);
        }
        return DFS(0, -1, adj, hasApple);
    }
};
```