File tree Expand file tree Collapse file tree
maximum-depth-of-binary-tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * class TreeNode {
4+ * val: number
5+ * left: TreeNode | null
6+ * right: TreeNode | null
7+ * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.left = (left===undefined ? null : left)
10+ * this.right = (right===undefined ? null : right)
11+ * }
12+ * }
13+ */
14+
15+ /*
16+ DFS로 노드를 탐색해가며 최대깊이를 찾는다
17+
18+ 시간 복잡도 : O(N - binary tree의 깊이)
19+
20+ */
21+
22+ function maxDepth ( root : TreeNode | null ) : number {
23+ let result = 0
24+ const search = ( node , floor ) => {
25+ if ( ! node ) return
26+ result = Math . max ( floor , result )
27+
28+ search ( node . left , floor + 1 )
29+ search ( node . right , floor + 1 )
30+ }
31+
32+ search ( root , 1 )
33+ return result
34+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * class ListNode {
4+ * val: number
5+ * next: ListNode | null
6+ * constructor(val?: number, next?: ListNode | null) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.next = (next===undefined ? null : next)
9+ * }
10+ * }
11+ */
12+
13+ /*
14+ 새 mergeList를 만들고 list1, list2를 순회하며 더 작은 값을 mergeList에 넣는다.
15+ 두 리스트의 next가 비게 되면 mergeList의 head를 리턴한다.
16+
17+ 시간복잡도 : O(N+K) (N은 list1의 길이, K는 list2의 길이)
18+
19+ */
20+
21+ function mergeTwoLists (
22+ list1 : ListNode | null ,
23+ list2 : ListNode | null ,
24+ ) : ListNode | null {
25+ let now = null
26+ let head = null
27+
28+ while ( list1 || list2 ) {
29+ if ( ! list2 || ( list1 && list1 . val <= list2 . val ) ) {
30+ if ( ! now ) {
31+ now = list1
32+ head = now
33+ } else {
34+ now . next = list1
35+ now = now . next
36+ }
37+ list1 = list1 . next
38+ } else {
39+ if ( ! now ) {
40+ now = list2
41+ head = now
42+ } else {
43+ now . next = list2
44+ now = now . next
45+ }
46+ list2 = list2 . next
47+ }
48+ }
49+
50+ return head
51+ }
You can’t perform that action at this time.
0 commit comments