1
var cnvrtAdjLst = (mat) => {2
//converts the list of edges to adjacency list4
for (let i = 0; i < mat.length; i++) {6
if (map[p] === undefined) map[p] = [c];9
if (map[c] === undefined) map[c] = [p];14
var minTime = function (n, edges, hasApple) {15
let adjList = cnvrtAdjLst(edges); //convert to adjacency list for undirected graph16
let visited = new Set(); // visited set for checking trivial loop17
let dfsForApples = (src, len) => {18
visited.add(src); // add root to visited set, as we start exploring the subtree19
let lengthFromNow = 0; //total length of path visited by each child, 0 if no child has apple20
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 length25
if (lengthFromNow > 0) {26
//if there is an apple present in the subtree27
return lengthFromNow + 2;28
} else if (hasApple[src]) {29
//if there is no apple in subtree but apple is present on the root node32
// if no apple is present in subtree37
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