✅C++ || Building Tree || Concise Explanation || Depth First Search
Intuition\nUse vector of unordered set to store all neighbours of each node.\n\nCount time in each subtree by using depth first search .\n \n# Approach\nFor eac
# Intuition\nUse vector of unordered set to store all neighbours of each node.\n\nCount time in each subtree by using depth first search .\n \n# Approach\nFor each node, calculate time of each of its subtree .\n ### Return Condition : \nIf current node also contains apple or subtree contains time(subtree ans !=0) , then return ans + 2 as current node will also contribute to total answer  \n ### Base Case : \n- If a node is leaf node , return 2 if it contains apple as it will consume 2 units of time from parent node to reach leaf node\n- else return 0.\n\n# Complexity\n- Time complexity : $$O(N)$$ (Traversing each node of tree)\n\n- Space complexity : $$O(N)$$ (Recursion call stack)\n\n# Code\n```\nclass Solution {\npublic:\n    int solve(int root,vector<unordered_set<int>>& graph,vector<bool>& hasApple,vector<int>& vis)\n    {\n        if(vis[root]) return 0;\n        if(graph[root].size()==0) return hasApple[root] ? 2 : 0;\n\n        vis[root]=1;\n\n        int ans=0;\n        for(int node:graph[root])\n        {\n            ans+=solve(node,graph,hasApple,vis);\n        }\n        return (ans || hasApple[root]) ? ans+2 : ans;\n    }\n    int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) \n    {\n        vector<unordered_set<int>>graph(n);\n        vector<int>vis(n,0);\n\n        for(auto it:edges)\n        {\n            graph[it[0]].insert(it[1]);\n            graph[it[1]].insert(it[0]);\n        }    \n        int ans=solve(0,graph,hasApple,vis);\n        return ans ? ans-2 : ans;\n    }\n};\n```
['Hash Table', 'Tree', 'Depth-First Search', 'C++']