Skip to content

Commit 7919536

Browse files
committed
graph valid tree solution
1 parent 48385f4 commit 7919536

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

graph-valid-tree/hyer0705.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
export class Solution {
4+
/**
5+
* @param n: An integer
6+
* @param edges: a list of undirected edges
7+
* @return: true if it's a valid tree, or false
8+
*/
9+
validTree(n: number, edges: number[][]): boolean {
10+
if (n === 0) return true;
11+
if (edges.length !== n - 1) return false;
12+
13+
const graph: number[][] = Array.from({ length: n }, () => []);
14+
15+
for (const [s, e] of edges) {
16+
graph[s].push(e);
17+
graph[e].push(s);
18+
}
19+
20+
const visited = new Set<number>();
21+
22+
const queue = [0];
23+
visited.add(0);
24+
25+
let pointer = 0;
26+
while (pointer < queue.length) {
27+
const currentNode = queue[pointer++];
28+
29+
for (const nextNode of graph[currentNode]) {
30+
if (!visited.has(nextNode)) {
31+
queue.push(nextNode);
32+
visited.add(nextNode);
33+
}
34+
}
35+
}
36+
37+
return visited.size === n;
38+
}
39+
}

0 commit comments

Comments
 (0)