Skip to content

Commit 6d67a79

Browse files
committed
add Graph Valid Tree solution
1 parent a84c382 commit 6d67a79

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

graph-valid-tree/HoonDongKang.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* [Problem]: [178] Graph Valid Tree
3+
* (https://www.lintcode.com/problem/178/)
4+
*/
5+
6+
export class Solution {
7+
/**
8+
* @param n: An integer
9+
* @param edges: a list of undirected edges
10+
* @return: true if it's a valid tree, or false
11+
*/
12+
//시간복잡도 O(n+e)
13+
//공간복잡도 O(n+e)
14+
validTree(n: number, edges: number[][]): boolean {
15+
const graph: number[][] = Array.from({ length: n }, () => []);
16+
for (const [a, b] of edges) {
17+
graph[a].push(b);
18+
graph[b].push(a);
19+
}
20+
21+
const visited = new Set<number>();
22+
23+
function hasCycle(node: number, prev: number): boolean {
24+
if (visited.has(node)) return true;
25+
visited.add(node);
26+
27+
for (const neighbor of graph[node]) {
28+
if (neighbor === prev) continue;
29+
if (hasCycle(neighbor, node)) return true;
30+
}
31+
return false;
32+
}
33+
34+
if (hasCycle(0, -1)) return false;
35+
36+
return visited.size === n;
37+
}
38+
39+
//시간복잡도 O(n)
40+
//공간복잡도 O(n)
41+
validTree2(n: number, edges: number[][]): boolean {
42+
if (edges.length !== n - 1) return false;
43+
44+
const graph: number[][] = Array.from({ length: n }, () => []);
45+
for (const [a, b] of edges) {
46+
graph[a].push(b);
47+
graph[b].push(a);
48+
}
49+
50+
const visited = new Set<number>();
51+
52+
function dfs(node: number) {
53+
visited.add(node);
54+
for (const neighbor of graph[node]) {
55+
if (!visited.has(neighbor)) {
56+
dfs(neighbor);
57+
}
58+
}
59+
}
60+
61+
dfs(0);
62+
63+
return visited.size === n;
64+
}
65+
}

0 commit comments

Comments
 (0)