-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
36 lines (34 loc) · 724 Bytes
/
index.js
File metadata and controls
36 lines (34 loc) · 724 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @param {number} n
* @param {number[][]} edges
* @return {boolean}
*/
var validTree = function(n, edges) {
const graph = createGraph(n, edges);
const visited = new Set();
if (hasCycle(graph, 0, null, visited)) {
return false;
}
return visited.size === n;
};
function hasCycle(graph, u, pre, visited) {
if (visited.has(u)) {
return true;
}
visited.add(u);
for (const v of graph[u]) {
if (v === pre) continue;
if (hasCycle(graph, v, u, visited)) {
return true;
}
}
return false;
}
function createGraph(n, edges) {
const graph = new Array(n).fill(null).map(() => []);
for (const [u, v] of edges) {
graph[u].push(v);
graph[v].push(u);
}
return graph;
}