File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ /**
3+ * @param {number } n
4+ * @param {number[][] } edges
5+ * @returns {boolean }
6+ */
7+ validTree ( n , edges ) {
8+ // A valid tree must have exactly n - 1 edges
9+ if ( edges . length !== n - 1 ) {
10+ return false ;
11+ }
12+
13+ // Initialize the adjacency list
14+ let graph = [ ] ;
15+ for ( let i = 0 ; i < n ; i ++ ) {
16+ graph . push ( [ ] ) ;
17+ }
18+
19+ // Populate the adjacency list with edges
20+ for ( let [ node , neighbor ] of edges ) {
21+ graph [ node ] . push ( neighbor ) ;
22+ graph [ neighbor ] . push ( node ) ;
23+ }
24+
25+ let visited = new Set ( ) ;
26+
27+ // Depth-First Search (DFS) to explore the graph
28+ function dfs ( node ) {
29+ visited . add ( node ) ;
30+ for ( let neighbor of graph [ node ] ) {
31+ if ( ! visited . has ( neighbor ) ) {
32+ dfs ( neighbor ) ;
33+ }
34+ }
35+ }
36+
37+ // Start DFS from node 0
38+ dfs ( 0 ) ;
39+
40+ // Check if all nodes were visited
41+ return visited . size === n ;
42+ }
43+ }
44+
45+ // TC: O(n)
46+ // SC: O(n)
You can’t perform that action at this time.
0 commit comments