Non-Recursive Solution - O(n) space, O(nlogn) runtime
\npublic int minTime(int n, int[][] edges, List<Boolean> hasApple) {\n\t// 1) find the arr of node parents arr[i] = parent(i)\n\t// 2) create a set of visited n
```\npublic int minTime(int n, int[][] edges, List<Boolean> hasApple) {\n\t// 1) find the arr of node parents arr[i] = parent(i)\n\t// 2) create a set of visited nodes\n\t// 3) for each of the apples find the path to root, minus already visited distances, add it to minDistance * 2 (there and back)\n\t// 4) return total\n\n\tMap<Integer, Integer> parent = new HashMap<>();\n\n\tfor (int[] edge : edges) {\n\t\tif (parent.containsKey(edge[1])) parent.put(edge[0], edge[1]);    \n\t\telse parent.put(edge[1], edge[0]);     \n\t}\n\n\tSet<Integer> visited = new HashSet<>();\n\tint total = 0;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tif (hasApple.get(i)) {\n\t\t\ttotal += pathToRoot(parent, i, visited);\n\t\t}\n\t}\n\treturn total;\n}\n\nprivate int pathToRoot(Map<Integer, Integer> parent, int node, Set<Integer> visited) {\n\tint count = 0;\n\n\twhile (node != 0 && !visited.contains(node)) {\n\t\tvisited.add(node);\n\t\tnode = parent.get(node);\n\t\tcount += 2;\n\t}\n\treturn count;\n}\n```
['Iterator', 'Java']