Skip to content

Commit a2918ef

Browse files
authored
[ PS ] : Graph Valid Tree
1 parent c94dacb commit a2918ef

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

graph-valid-tree/uraflower.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @returns {boolean}
5+
*/
6+
function validTree(n, edges) {
7+
// 트리의 조건을 만족하는지 확인(V = E + 1)
8+
if (edges.length !== n - 1) {
9+
return false;
10+
}
11+
12+
const graph = Array.from({ length: n }).map(() => []);
13+
14+
for (const [u, v] of edges) {
15+
graph[u].push(v);
16+
graph[v].push(u);
17+
}
18+
19+
const queue = [[-1, 0]]; // 부모 노드, 자식 노드
20+
const visited = new Set();
21+
22+
while (queue.length) {
23+
const [parent, current] = queue.shift();
24+
if (visited.has(current)) {
25+
return false;
26+
}
27+
visited.add(current);
28+
29+
for (const neighbor of graph[current]) {
30+
if (neighbor === parent) continue;
31+
queue.push([current, neighbor]);
32+
}
33+
}
34+
35+
return visited.size === n;
36+
}
37+
38+
// 시간복잡도: O(V + E)
39+
// 공간복잡도: O(V)

0 commit comments

Comments
 (0)