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.
1#include <stdbool.h>
2#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
5
6int timeRequired = 0;
7
8void dfs(int node, int parent, int** adjList, int* adjSize, bool* hasApple) {
9 for (int i = 0; i < adjSize[node]; ++i) {
10 int child = adjList[node][i];
11 if (child == parent) continue;
12 dfs(child, node, adjList, adjSize, hasApple);
13 if (hasApple[child]) {
14 timeRequired += 2;
15 hasApple[node] = true;
16 }
17 }
18}
19
20int minTime(int n, int** edges, int edgesSize, bool* hasApple) {
21 int* adjSize = (int*)calloc(n, sizeof(int));
22 int** adjList = (int**)malloc(n * sizeof(int*));
23
24 for (int i = 0; i < n; ++i) {
25 adjList[i] = (int*)malloc((n - 1) * sizeof(int));
26 }
27
28 for (int i = 0; i < edgesSize; ++i) {
29 int u = edges[i][0];
30 int v = edges[i][1];
31 adjList[u][adjSize[u]++] = v;
32 adjList[v][adjSize[v]++] = u;
33 }
34
35 dfs(0, -1, adjList, adjSize, hasApple);
36
37 for (int i = 0; i < n; ++i) {
38 free(adjList[i]);
39 }
40 free(adjList);
41 free(adjSize);
42
43 return timeRequired;
44}
The C solution implements the DFS traversal with a recursive function. An adjacency list represents the graph, and we use it to explore each node's children. We check if a child (subtree) has apples; if so, we add 2 to the total time, accounting for both the forward and return traversal.
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.
DFS fits the recursive, path-specific needs over BFS here, which tracks broader levels.