MediumNo. 1443
Minimum Time to Collect All Apples in a Tree — LeetCode 1443 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table
- Reading time
- 3 min
- Source
- leetcode.com
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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0690 | Employee Importance | Medium |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
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.