Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1443. Minimum Time to Collect All Apples in a Tree

Explanation:

To solve this problem, we can use a depth-first search (DFS) algorithm to traverse the tree and keep track of the minimum time it takes to collect all apples. We can start from the root node (vertex 0) and recursively visit all the children nodes.

  1. Perform a DFS starting from the root node (vertex 0).
  2. Keep track of the time taken to reach each node and collect all apples on the path.
  3. Return the total time taken to collect all apples in the tree.

Solution (Java):

class Solution {
    public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
        Map<Integer, List<Integer>> tree = new HashMap<>();
        for (int[] edge : edges) {
            tree.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
            tree.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
        }
        return dfs(tree, 0, hasApple, new boolean[n]);
    }

    private int dfs(Map<Integer, List<Integer>> tree, int node, List<Boolean> hasApple, boolean[] visited) {
        visited[node] = true;
        int time = 0;
        for (int child : tree.getOrDefault(node, new ArrayList<>())) {
            if (!visited[child]) {
                time += dfs(tree, child, hasApple, visited);
            }
        }
        if ((time > 0 || hasApple.get(node)) && node != 0) {
            time += 2;
        }
        return time;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.