LeetCode 1443: Minimum Time to Collect All Apples in a Tree Solution

Master LeetCode problem 1443 (Minimum Time to Collect All Apples in a Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1443. Minimum Time to Collect All Apples in a Tree

Problem Explanation

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):

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1443 (Minimum Time to Collect All Apples in a Tree)?

This page provides optimized solutions for LeetCode problem 1443 (Minimum Time to Collect All Apples in a Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1443 (Minimum Time to Collect All Apples in a Tree)?

The time complexity for LeetCode 1443 (Minimum Time to Collect All Apples in a Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1443 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1443 in Java, C++, or Python.

Back to LeetCode Solutions