Skip to content

Commit 5ba1835

Browse files
committed
Feat: 261. Graph Valid Tree
1 parent 7e77421 commit 5ba1835

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

graph-valid-tree/HC-kang.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* https://leetcode.com/problems/graph-valid-tree
3+
* T.C. O(n)
4+
* S.C. O(n)
5+
*/
6+
function validTree(n: number, edges: number[][]): boolean {
7+
if (edges.length !== n - 1) return false;
8+
9+
const parent = Array.from({ length: n }, (_, i) => i);
10+
11+
// find and compress path
12+
function find(x: number): number {
13+
if (parent[x] !== x) {
14+
parent[x] = find(parent[x]);
15+
}
16+
return parent[x];
17+
}
18+
19+
// union two sets and check if they have the same root
20+
function union(x: number, y: number): boolean {
21+
const rootX = find(x);
22+
const rootY = find(y);
23+
if (rootX === rootY) return false;
24+
parent[rootX] = rootY;
25+
return true;
26+
}
27+
28+
for (const [x, y] of edges) {
29+
if (!union(x, y)) return false;
30+
}
31+
32+
return true;
33+
}

0 commit comments

Comments
 (0)