File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ // V: Node 개수, E: 간선의 개수
2+ // 시간복잡도: O(V + E)
3+ // 공간복잡도: O(V + E)
4+
5+ class Solution {
6+ /**
7+ * @param {number } n
8+ * @param {number[][] } edges
9+ * @returns {boolean }
10+ */
11+ validTree ( n , edges ) {
12+ const graph = new Map ( ) ;
13+
14+ for ( let [ u , v ] of edges ) {
15+ if ( ! graph . has ( u ) ) graph . set ( u , [ ] )
16+ if ( ! graph . has ( v ) ) graph . set ( v , [ ] )
17+ graph . get ( u ) . push ( v )
18+ graph . get ( v ) . push ( u )
19+ }
20+
21+ const visited = Array . from ( { length : n } , ( ) => false ) ;
22+
23+ let edgeCount = 0 ;
24+ const queue = [ 0 ] ;
25+ visited [ 0 ] = true
26+
27+ while ( queue . length ) {
28+ const cur = queue . shift ( ) ;
29+
30+ for ( const edge of graph . get ( cur ) || [ ] ) {
31+ if ( ! visited [ edge ] ) {
32+ visited [ edge ] = true ;
33+ queue . push ( edge )
34+ }
35+ edgeCount ++ ;
36+ }
37+ }
38+
39+ const isAllVisited = visited . every ( ( visited ) => visited === true )
40+
41+ return isAllVisited && ( edgeCount / 2 ) === ( n - 1 )
42+ }
43+
44+
45+ }
Original file line number Diff line number Diff line change 1+ // 시간복잡도: O(n)
2+ // 공간복잡도: O(n)
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * function TreeNode(val, left, right) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.left = (left===undefined ? null : left)
9+ * this.right = (right===undefined ? null : right)
10+ * }
11+ */
12+ /**
13+ * @param {TreeNode } root
14+ * @return {number }
15+ */
16+ var maxDepth = function ( root ) {
17+ if ( ! root ) return 0 ;
18+
19+ let maxDepth = 0 ;
20+ const exploreMaxDepth = ( node , depth ) => {
21+ if ( ! node ) {
22+ maxDepth = Math . max ( maxDepth , depth )
23+ return
24+ }
25+
26+
27+ exploreMaxDepth ( node . left , depth + 1 )
28+ exploreMaxDepth ( node . right , depth + 1 )
29+ }
30+
31+ exploreMaxDepth ( root , 0 )
32+
33+ return maxDepth
34+ } ;
You can’t perform that action at this time.
0 commit comments