File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } n
3+ * @param {number[][] } edges
4+ * @returns {boolean }
5+ */
6+ function validTree ( n , edges ) {
7+ // 트리의 조건을 만족하는지 확인(V = E + 1)
8+ if ( edges . length !== n - 1 ) {
9+ return false ;
10+ }
11+
12+ const graph = Array . from ( { length : n } ) . map ( ( ) => [ ] ) ;
13+
14+ for ( const [ u , v ] of edges ) {
15+ graph [ u ] . push ( v ) ;
16+ graph [ v ] . push ( u ) ;
17+ }
18+
19+ const queue = [ [ - 1 , 0 ] ] ; // 부모 노드, 자식 노드
20+ const visited = new Set ( ) ;
21+
22+ while ( queue . length ) {
23+ const [ parent , current ] = queue . shift ( ) ;
24+ if ( visited . has ( current ) ) {
25+ return false ;
26+ }
27+ visited . add ( current ) ;
28+
29+ for ( const neighbor of graph [ current ] ) {
30+ if ( neighbor === parent ) continue ;
31+ queue . push ( [ current , neighbor ] ) ;
32+ }
33+ }
34+
35+ return visited . size === n ;
36+ }
37+
38+ // 시간복잡도: O(V + E)
39+ // 공간복잡도: O(V)
You can’t perform that action at this time.
0 commit comments