Skip to content

Commit d3faab0

Browse files
authored
Create 1443-minimum-time-to-collect-all-apples-in-a-tree.js
1 parent 44b0e00 commit d3faab0

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* DFS
3+
* Time O(n) | Space O(n)
4+
* https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
5+
* @param {number} n
6+
* @param {number[][]} edges
7+
* @param {boolean[]} hasApple
8+
* @return {number}
9+
*/
10+
var minTime = function(n, edges, hasApple) {
11+
12+
if(n === 1) return 0;
13+
14+
const tree = {};
15+
16+
for(let i = 0; i < edges.length; i++) {
17+
18+
const parent = edges[i][0];
19+
const child = edges[i][1];
20+
21+
if(!tree[parent]) {
22+
tree[parent] = [];
23+
}
24+
25+
if(!tree[child]) {
26+
tree[child] = [];
27+
};
28+
29+
tree[child].push(parent);
30+
tree[parent].push(child);
31+
}
32+
33+
const dfs = (curr, pre) => {
34+
35+
let pathLen = 0;
36+
for(const nextNode of tree[curr]) {
37+
if(nextNode === pre) continue;
38+
pathLen += dfs(nextNode, curr);
39+
}
40+
41+
if(pathLen > 0 || hasApple[curr]) return pathLen+2;
42+
return 0;
43+
}
44+
45+
const result = dfs(0, -1) - 2;
46+
return (result > 0 && result) || 0;
47+
};

0 commit comments

Comments
 (0)