Minimum Time to Collect All Apples in a Tree LeetCode solution in JavaScript

1
var cnvrtAdjLst = (mat) => {
2
//converts the list of edges to adjacency list
3
let map = new Map();
4
for (let i = 0; i < mat.length; i++) {
5
let [p, c] = mat[i];
6
if (map[p] === undefined) map[p] = [c];
7
else map[p].push(c);
8

9
if (map[c] === undefined) map[c] = [p];
10
else map[c].push(p);
11
}
12
return map;
13
};
14
var minTime = function (n, edges, hasApple) {
15
let adjList = cnvrtAdjLst(edges); //convert to adjacency list for undirected graph
16
let visited = new Set(); // visited set for checking trivial loop
17
let dfsForApples = (src, len) => {
18
visited.add(src); // add root to visited set, as we start exploring the subtree
19
let lengthFromNow = 0; //total length of path visited by each child, 0 if no child has apple
20
for (let i in adjList[src]) {
21
if (!visited.has(adjList[src][i])) {
22
lengthFromNow += dfsForApples(adjList[src][i], len + 1); // add child path length to total length
23
}
24
}
25
if (lengthFromNow > 0) {
26
//if there is an apple present in the subtree
27
return lengthFromNow + 2;
28
} else if (hasApple[src]) {
29
//if there is no apple in subtree but apple is present on the root node
30
return 2;
31
} else {
32
// if no apple is present in subtree
33
return 0;
34
}
35
};
36
visited.add(0);
37
let res = dfsForApples(0, 0);
38
return res ? res - 2 : 0; //check if the root node itself has an apple or no apple is present
39
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0