Explained : JAVA solution | DFS | O(n)
\n#### DFS Solution \nWe go to every child node of the current node and check if it has an apple or not if it has an apple , we add 2 (one to go and one to retu
\n#### DFS Solution \nWe **go to every child node of the current node** and check if it has an apple or not if it has an apple , we add 2 (one to go and one to return) for every node if any child node had an apple. If none of its children had an apple we return 0 + 2 if the current node has an apple else we just return 0.\n\n* If any of the children has an apple we return **2 + sum of children**\n* If none of the childrem has an apple ( sum=0 ) but the current has an apple we return 2 + sum = **2**\n* If neither the current node or any of its children has an apple we just **return 0**\n\n##### Time complexity: O(n)\n\n```\nclass Solution \n{\n    public int minTime(int n, int[][] edges, List<Boolean> hasApple) \n    {\n        List<Integer>[] canVisit = new ArrayList[n];\n        \n        //Creating adjacency list\n        for(int i = 0; i<n; i++)\n        {\n            canVisit[i] = new ArrayList<>();\n        }\n        for(int[] edge : edges)\n        {\n            canVisit[edge[0]].add(edge[1]);            \n            canVisit[edge[1]].add(edge[0]);\n        }\n        \n        boolean[] visited = new boolean[n];\n        return helper(0,hasApple,canVisit,visited);\n        \n    }\n    int helper(int i, List<Boolean> hasApple, List<Integer>[] canVisit, boolean[] visited)\n    {\n        if(visited[i]) return 0;\n        visited[i] = true;\n        \n        // Visiting every child node\n        int sum = 0;\n        for(int edge : canVisit[i])\n        {\n            sum += helper(edge, hasApple, canVisit, visited);\n        }\n        \n        if(i==0) return  sum; // Special case for the root node\n        \n        // If any children contain an apple or the current node contains an apple we return (2+sum)\n        if(hasApple.get(i) || sum>0 ) return (2 + sum); \n        \n        //If neither the children or the current node contain an apple we just return 0\n        else return 0;        \n    }\n}\n```
['Java']