Sponsored
Sponsored
This approach involves using Depth-First Search (DFS) to traverse the tree from the root node (vertex 0). We recursively explore each subtree from the current node. If a subtree contains any apples, we add the cost of traversing to and from that subtree (2 units of time per edge, as we have to go there and come back). This ensures that the solution captures only the necessary paths contributing to the apple collection.
Time Complexity: O(n), where n is the number of vertices. We explore each vertex once in the DFS traversal.
Space Complexity: O(n), for storing the adjacency list and recursion stack.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MinTime(int n, int[][] edges, IList<bool> hasApple) {
6 List<int>[] adj = new List<int>[n];
7 for (int i = 0; i < n; i++) adj[i] = new List<int>();
8 foreach (var edge in edges) {
9 adj[edge[0]].Add(edge[1]);
10 adj[edge[1]].Add(edge[0]);
11 }
12 return DFS(0, -1, adj, hasApple);
13 }
14
15 private int DFS(int node, int parent, List<int>[] adj, IList<bool> hasApple) {
16 int total_time = 0;
17 foreach (int child in adj[node]) {
18 if (child == parent) continue;
19 int child_time = DFS(child, node, adj, hasApple);
20 if (child_time > 0 || hasApple[child]) {
21 total_time += child_time + 2;
22 }
23 }
24 return total_time;
25 }
26}
The C# solution employs DFS similarly, using adjacency lists formed from the edges. Recursion is used to perform comparisons and selectively add to the traversal cost if apples are located on pathways.
Though less intuitive for this problem compared to DFS, a Breadth-First Search (BFS) approach can be implemented to calculate the shortest paths considering leaf nodes. This method explores layers of the tree level by level but is not more efficient in this specific context than DFS, given that we only need to find necessary paths.
Time Complexity: O(n) in BFS general terms, still visiting nodes.
Space Complexity: O(n), by the queue usage.
BFS visitations may suit other tree tasks. This requires depth consideration with DFS strategies instead.