Skip to content

Commit a33606f

Browse files
authored
Merge pull request #553 from Sunjae95/main
[선재] WEEK11 Solutions
2 parents ba77b9c + 795c47a commit a33606f

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* 최대 깊이를 탐색하는 문제여서 dfs를 먼저 떠올렸지만 이번에 bfs로 풀이하고 싶어 bfs로 풀었습니다.
4+
*
5+
* n = total node count
6+
* time complexity: O(n)
7+
* space complexity: O(n)
8+
*/
9+
var maxDepth = function (root) {
10+
const queue = [];
11+
let lastIndex = queue.length;
12+
let answer = 0;
13+
14+
if (!root) return answer;
15+
16+
queue.push(root);
17+
18+
while (queue.length !== lastIndex) {
19+
let currentCount = queue.length - lastIndex;
20+
answer++;
21+
22+
while (currentCount--) {
23+
let currentNode = queue[lastIndex];
24+
lastIndex++;
25+
if (currentNode.left) queue.push(currentNode.left);
26+
if (currentNode.right) queue.push(currentNode.right);
27+
}
28+
}
29+
30+
return answer;
31+
};

reorder-list/sunjae95.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @description
3+
* 인덱스로 접근하지 못하는 구조를 인덱스로 접근하게 하여 two pointer로 풀이
4+
*
5+
* n = total node count
6+
* time complexity: O(n)
7+
* space complexity: O(n)
8+
*/
9+
var reorderList = function (head) {
10+
// convert from queue to list
11+
let travelNode = head;
12+
const list = [];
13+
while (travelNode) {
14+
list.push(travelNode);
15+
travelNode = travelNode.next;
16+
}
17+
// two pointer
18+
let [left, right] = [0, list.length - 1];
19+
const node = new ListNode();
20+
let tail = node;
21+
22+
while (left <= right) {
23+
// 1. left append
24+
const leftNode = list[left];
25+
leftNode.next = null;
26+
tail.next = leftNode;
27+
tail = leftNode;
28+
// 2. conditional right append
29+
const rightNode = list[right];
30+
rightNode.next = null;
31+
if (left !== right) {
32+
tail.next = rightNode;
33+
tail = rightNode;
34+
}
35+
36+
left++;
37+
right--;
38+
}
39+
40+
head = node.next;
41+
};

0 commit comments

Comments
 (0)