File tree 2 files changed +73
-0
lines changed
maximum-depth-of-binary-tree
2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TreeNode {
2
+ val : number ;
3
+ left : TreeNode | null ;
4
+ right : TreeNode | null ;
5
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
6
+ this . val = val === undefined ? 0 : val ;
7
+ this . left = left === undefined ? null : left ;
8
+ this . right = right === undefined ? null : right ;
9
+ }
10
+ }
11
+
12
+ /**
13
+ * @link https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
14
+ *
15
+ * 접근 방법 : DFS 사용
16
+ * - 각 노드에서 왼쪽 서브트리와 오른쪽 서브트리 깊이 계산한 후, 더 깊은 값에 1 더하기
17
+ * - 종료 조건 : 노드가 null일 때 0 반환
18
+ *
19
+ * 시간복잡도 : O(n)
20
+ * - n = 트리의 노드 개수
21
+ * - 노드 한 번씩 방문해서 깊이 계산
22
+ *
23
+ * 공간복잡도 : O(n)
24
+ * - 기울어진 트리의 경우, 트리 최대 깊이만큼 재귀 호출 스택 쌓임
25
+ */
26
+ function maxDepth ( root : TreeNode | null ) : number {
27
+ if ( ! root ) return 0 ;
28
+
29
+ return Math . max ( maxDepth ( root . left ) , maxDepth ( root . right ) ) + 1 ;
30
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @link https://leetcode.com/problems/merge-intervals/
3
+ *
4
+ * 접근 방법 :
5
+ * - 인터벌 배열 첫 번째 요소 기준으로 오름차순 정렬
6
+ * - 인터벌의 시작이 이전 인터벌 끝보다 작으면 범위 업데이트
7
+ * - 범위에 속하지 않으면 현재 인터벌을 결과 배열에 추가하고 새로운 인터벌로 업데이트
8
+ *
9
+ * 시간복잡도 : O(nlogn)
10
+ * - n = 인터벌 배열의 길이
11
+ * - 인터벌 배열 정렬 : O(nlogn)
12
+ * - 병합 과정: O(n)
13
+ *
14
+ * 공간복잡도 : O(n)
15
+ * - 결과 배열에 담아서 리턴
16
+ */
17
+ function merge ( intervals : number [ ] [ ] ) : number [ ] [ ] {
18
+ const result : number [ ] [ ] = [ ] ;
19
+
20
+ if ( intervals . length < 2 ) return intervals ;
21
+
22
+ // 첫번째 요소 기준으로 정렬
23
+ const sortedIntervals = intervals . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
24
+
25
+ let [ start , end ] = sortedIntervals [ 0 ] ;
26
+
27
+ for ( let i = 1 ; i < sortedIntervals . length ; i ++ ) {
28
+ const [ newStart , newEnd ] = sortedIntervals [ i ] ;
29
+ if ( newStart <= end ) {
30
+ // 범위 겹치는 경우, end 업데이트
31
+ end = Math . max ( end , newEnd ) ;
32
+ } else {
33
+ // 겹치지 않는 경우, 현재 구간 추가하고 새로운 구간으로 업데이트
34
+ result . push ( [ start , end ] ) ;
35
+ [ start , end ] = [ newStart , newEnd ] ;
36
+ }
37
+ }
38
+
39
+ // 마지막 구간 추가
40
+ result . push ( [ start , end ] ) ;
41
+
42
+ return result ;
43
+ }
You can’t perform that action at this time.
0 commit comments