File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments