🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
\uD83D\uDD34 Check out LeetCode The Hard Way for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our Discord for live discussion.\n\uD83D\uDF
\uD83D\uDD34 Check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord](https://discord.gg/Nqm4jJcyBf) for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast](https://www.youtube.com/watch?v=5haVLZv_zg0&list=PLBu4Bche1aEWMj1TdpymXbD8Tn8xKVYwj&index=11) if you are interested.\n\n```cpp\nclass Solution {\npublic:\n    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {\n        vector<vector<int>> g(n);\n        for (auto x : edges) {\n\t\t\t// x[0] can go to x[1]\n            g[x[0]].push_back(x[1]);\n\t\t\t// x[1] can go to x[0]\n            g[x[1]].push_back(x[0]);\n        }\n        // u = current vertex\n        // p = parent vertex\n        function<int(int, int)> dfs = [&] (int u, int p) {\n            int res = 0, t = 0;\n\t\t\t// go to each child\n            for (auto v : g[u]) {\n                // if v is not same as p\n                if (p ^ v) {\n                    // calculate the child time\n                    t = dfs(v, u);\n                    // if there is an apple in the subtree, we need 2 seconds to collect it and head back\n                    // if we are in vertex 1, we need 4 seconds to collect all the apples in 4 & 5 \n                    // so if we are in vertex 1, we need 4 seconds to collect the apples in 4 & 5\n                    // how does 0 know 1 has collected the apple? check the time, i.e. `t`\n                    // if t > 0, it means we got some apples in sub trees\n                    if (t > 0 || hasApple[v]) {\n                        res += t + 2;\n                    }\n                }\n            }\n            return res;\n        };\n        return dfs(0, -1);\n    }\n};\n```
['Tree', 'Depth-First Search', 'C', 'C++']