File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/maximum-depth-of-binary-tree/
3+ * time complexity : O(n)
4+ * space complexity : O(n)
5+ */
6+
7+ export class TreeNode {
8+ val : number
9+ left : TreeNode | null
10+ right : TreeNode | null
11+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
12+ this . val = ( val === undefined ? 0 : val )
13+ this . left = ( left === undefined ? null : left )
14+ this . right = ( right === undefined ? null : right )
15+ }
16+ }
17+
18+ export function maxDepth ( root : TreeNode | null ) : number {
19+ if ( ! root ) return 0 ;
20+
21+ return Math . max ( maxDepth ( root . left ) , maxDepth ( root . right ) ) + 1 ;
22+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/reorder-list/
3+ * time complexity : O(n)
4+ * space complexity : O(1)
5+ */
6+
7+ class ListNode {
8+ val : number
9+ next : ListNode | null
10+ constructor ( val ?: number , next ?: ListNode | null ) {
11+ this . val = ( val === undefined ? 0 : val )
12+ this . next = ( next === undefined ? null : next )
13+ }
14+ }
15+
16+ function reorderList ( head : ListNode | null ) : void {
17+ if ( ! head || ! head . next ) return ;
18+
19+ // 1. 중간 지점 찾기 (Floyd’s Tortoise and Hare)
20+ let slow : ListNode | null = head ;
21+ let fast : ListNode | null = head ;
22+
23+ while ( fast && fast . next ) {
24+ slow = slow ! . next ;
25+ fast = fast . next . next ;
26+ }
27+
28+ // 2. 중간 이후의 리스트 뒤집기
29+ let prev : ListNode | null = null ;
30+ let curr : ListNode | null = slow ;
31+
32+ while ( curr ) {
33+ const next = curr . next ;
34+ curr . next = prev ;
35+ prev = curr ;
36+ curr = next ;
37+ }
38+
39+ // 3. 앞부분과 뒤집어진 후반부 병합
40+ let first : ListNode | null = head ;
41+ let second : ListNode | null = prev ;
42+
43+ while ( second && second . next ) {
44+ const temp1 = first ! . next ;
45+ const temp2 = second . next ;
46+
47+ first ! . next = second ;
48+ second . next = temp1 ;
49+
50+ first = temp1 ;
51+ second = temp2 ;
52+ }
53+ } ;
You can’t perform that action at this time.
0 commit comments