๐ณ Collect Coins in a Tree
Imagine you're a treasure hunter exploring a mystical tree-shaped network of caves. Each cave (node) may contain a magical coin, and you can collect all coins within a distance of 2 from your current position without moving!
You start at any cave of your choice and can perform two operations:
- Collect: Gather all coins within distance โค 2 from your current cave
- Move: Travel to any directly connected cave (costs 1 edge traversal)
Your mission: Find the minimum number of edges you need to traverse to collect all coins and return to your starting cave. Remember, each edge traversal counts separately - if you pass through the same edge multiple times, count it each time!
Input: An integer n (number of caves), a 2D array edges defining the tree structure, and a binary array coins where coins[i] = 1 means cave i contains a coin.
Output: Return the minimum number of edge traversals needed.
Input & Output
Time & Space Complexity
Single pass through all nodes and edges for trimming operations
Space for adjacency list and degree arrays
Constraints
- 1 โค n โค 3 ร 104
- coins.length == n
- coins[i] is either 0 or 1
- edges.length == n - 1
- edges[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- The edges represent a valid tree structure
- There is at least one coin in the tree