File tree Expand file tree Collapse file tree 3 files changed +80
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 3 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * 동일한 depth를 방문해야하므로 bfs 및 트리 순회
4+ *
5+ * n = length of node of root
6+ * time complexity: O(n)
7+ * space complexity: O(n)
8+ */
9+ var levelOrder = function ( root ) {
10+ if ( ! root ) return [ ] ;
11+
12+ const answer = [ ] ;
13+ const queue = [ root ] ;
14+ let queueCurrentIndex = 0 ;
15+
16+ while ( queue . length > queueCurrentIndex ) {
17+ answer . push ( [ ] ) ;
18+ const answerLastIndex = answer . length - 1 ;
19+ const depthEndIndex = queue . length ;
20+
21+ while ( depthEndIndex !== queueCurrentIndex ) {
22+ const tree = queue [ queueCurrentIndex ++ ] ;
23+
24+ answer [ answerLastIndex ] . push ( tree . val ) ;
25+ if ( tree . left ) queue . push ( tree . left ) ;
26+ if ( tree . right ) queue . push ( tree . right ) ;
27+ }
28+ }
29+
30+ return answer ;
31+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * 점화식: dp[i] = Math.max(dp[i - 1], dp[i - 2] + current);
4+ * 순회한다는 조건이 있으므로 다음과 같이 분기처리 할 수 있다.
5+ * 1. 처음이 선택 O 마지막 X
6+ * 2. 처음이 선택 X 마지막 상관없음
7+ *
8+ * n = length of nums
9+ * time complexity: O(n)
10+ * space complexity: O(n)
11+ */
12+ var rob = function ( nums ) {
13+ if ( nums . length === 1 ) return nums [ 0 ] ;
14+ if ( nums . length === 2 ) return Math . max ( nums [ 0 ] , nums [ 1 ] ) ;
15+
16+ const hasFirst = Array . from ( { length : nums . length } , ( _ , i ) =>
17+ i < 2 ? nums [ 0 ] : 0
18+ ) ;
19+ const noFirst = Array . from ( { length : nums . length } , ( _ , i ) =>
20+ i === 1 ? nums [ i ] : 0
21+ ) ;
22+ for ( let i = 2 ; i < nums . length ; i ++ ) {
23+ hasFirst [ i ] = Math . max ( hasFirst [ i - 1 ] , hasFirst [ i - 2 ] + nums [ i ] ) ;
24+ noFirst [ i ] = Math . max ( noFirst [ i - 1 ] , noFirst [ i - 2 ] + nums [ i ] ) ;
25+ if ( i === nums . length - 1 ) {
26+ hasFirst [ i ] = Math . max ( hasFirst [ i - 1 ] , hasFirst [ i - 2 ] ) ;
27+ }
28+ }
29+
30+ return Math . max ( hasFirst [ nums . length - 1 ] , noFirst [ nums . length - 1 ] ) ;
31+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ *
4+ * n = length of n
5+ * time complexity: O(n)
6+ * space complexity: O(n)
7+ */
8+ var reverseBits = function ( n ) {
9+ let answer = 0 ;
10+ let binary = n . toString ( 2 ) ;
11+
12+ if ( binary . length < 32 ) binary = "0" . repeat ( 32 - binary . length ) + binary ;
13+
14+ for ( let i = binary . length - 1 ; i >= 0 ; i -- )
15+ answer += Math . pow ( 2 , i ) * Number ( binary [ i ] ) ;
16+
17+ return answer ;
18+ } ;
You can’t perform that action at this time.
0 commit comments