forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHoonDongKang.ts
More file actions
65 lines (53 loc) · 1.68 KB
/
HoonDongKang.ts
File metadata and controls
65 lines (53 loc) · 1.68 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* [Problem]: [178] Graph Valid Tree
* (https://www.lintcode.com/problem/178/)
*/
export class Solution {
/**
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
//시간복잡도 O(n+e)
//공간복잡도 O(n+e)
validTree(n: number, edges: number[][]): boolean {
const graph: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const visited = new Set<number>();
function hasCycle(node: number, prev: number): boolean {
if (visited.has(node)) return true;
visited.add(node);
for (const neighbor of graph[node]) {
if (neighbor === prev) continue;
if (hasCycle(neighbor, node)) return true;
}
return false;
}
if (hasCycle(0, -1)) return false;
return visited.size === n;
}
//시간복잡도 O(n)
//공간복잡도 O(n)
validTree2(n: number, edges: number[][]): boolean {
if (edges.length !== n - 1) return false;
const graph: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const visited = new Set<number>();
function dfs(node: number) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
}
dfs(0);
return visited.size === n;
}
}