Skip to content

Commit c6ddebb

Browse files
authored
Merge pull request #1341 from froggy1014/week4
[froggy1014] Week 04 Solutions
2 parents 5418c6d + 0de4758 commit c6ddebb

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// 시간복잡도: O(n) 모든 노드를 한번씩 방문하기 때문에 n
2+
// 공간복잡도: O(n) 최악의 경우 모든 노드가 한줄로 이어져 있을 때 스택에 모든 노드를 저장해야 하기 때문에 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+
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
20+
};
21+
22+
console.log(maxDepth([3, 9, 20, null, null, 15, 7]));
23+
console.log(maxDepth([1, null, 2]));

merge-two-sorted-lists/froggy1014.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// 시간 복잡도는 list1과 list2의 길이를 더한 것이다. 그래서 O(n + m)
2+
// 공간 복잡도는 알고리즘에서 사용하는 새로운 메모리는 없다. 그래서 O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* @param {ListNode} list1
13+
* @param {ListNode} list2
14+
* @return {ListNode}
15+
*/
16+
var mergeTwoLists = function (list1, list2) {
17+
if (list1 === null) return list2;
18+
if (list2 === null) return list1;
19+
20+
let start = new ListNode();
21+
let current = start;
22+
23+
while (list1 !== null && list2 !== null) {
24+
if (list1.val <= list2.val) {
25+
current.next = list1;
26+
list1 = list1.next;
27+
} else {
28+
current.next = list2;
29+
list2 = list2.next;
30+
}
31+
current = current.next;
32+
}
33+
34+
current.next = list1 || list2;
35+
36+
return start.next;
37+
};

0 commit comments

Comments
 (0)