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

MediumTreeDepth-First SearchBreadth-First SearchHash Table
Problem
#1443
Reading time
3 min

The problem

Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree.

Example

Input
n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output
8
Explanation
The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

Python solution

Python
class Solution:
    def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
        def dfs(u, cost):
            if vis[u]:
                return 0
            vis[u] = True
            nxt_cost = 0
            for v in g[u]:
                nxt_cost += dfs(v, 2)
            if not hasApple[u] and nxt_cost == 0:
                return 0
            return cost + nxt_cost

        g = defaultdict(list)
        for u, v in edges:
            g[u].append(v)
            g[v].append(u)
        vis = [False] * n
        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1443. Minimum Time to Collect All Apples in a Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1443. Minimum Time to Collect All Apples in a Tree?
LeetCode 1443. Minimum Time to Collect All Apples in a Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1443. Minimum Time to Collect All Apples in a Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1443. Minimum Time to Collect All Apples in a Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1443. Minimum Time to Collect All Apples in a Tree cover?
LeetCode 1443. Minimum Time to Collect All Apples in a Tree is tagged Tree, Depth-First Search, Breadth-First Search and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview