Skip to content

Commit e30a499

Browse files
committed
10주차
1 parent 3ac0528 commit e30a499

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed

invert-binary-tree/jdalma.kt

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
class `invert-binary-tree` {
7+
8+
fun invertTree(root: TreeNode?): TreeNode? {
9+
if (root == null) return null
10+
11+
return usingStack(root)
12+
}
13+
14+
/**
15+
* TC: O(n), SC: O(n)
16+
*/
17+
private fun usingDFS(node: TreeNode?): TreeNode? {
18+
if (node == null) return null
19+
20+
val (left, right) = node.left to node.right
21+
node.left = usingDFS(right)
22+
node.right = usingDFS(left)
23+
24+
return node
25+
}
26+
27+
/**
28+
* TC: O(n), SC: O(n)
29+
*/
30+
private fun usingStack(node: TreeNode): TreeNode {
31+
val stack= ArrayDeque<TreeNode>().apply {
32+
this.add(node)
33+
}
34+
35+
while (stack.isNotEmpty()) {
36+
val now = stack.removeLast()
37+
val tmp = now.left
38+
now.left = now.right
39+
now.right = tmp
40+
41+
now.left?.let { stack.add(it) }
42+
now.right?.let { stack.add(it) }
43+
}
44+
return node
45+
}
46+
47+
@Test
48+
fun `전달된 노드의 하위 노드들의 반전된 값을 반환한다`() {
49+
val actual = TreeNode.of(4,2,7,1,3,6,9)
50+
val expect = TreeNode.of(4,7,2,9,6,3,1)
51+
invertTree(actual) shouldBe expect
52+
53+
val actual1 = TreeNode.of(1,2)
54+
val expect1 = TreeNode.of(1,null,2)
55+
56+
invertTree(actual1) shouldBe expect1
57+
}
58+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
class `search-in-rotated-sorted-array` {
7+
8+
/**
9+
* O(log n)만큼의 시간만으로 해결해야 한다.
10+
* nums 배열은 정렬되어있지만 순환된 배열이므로 target 을 찾기 위한 일반적인 이분 탐색으로는 해결할 수 없다.
11+
* TC: O(log n), SC: O(1)
12+
*/
13+
fun search(nums: IntArray, target: Int): Int {
14+
var (low, high) = 0 to nums.size - 1
15+
16+
while (low + 1 < high) {
17+
val mid = (low + high) / 2
18+
19+
if (nums[mid] == target) {
20+
return mid
21+
}
22+
if (nums[low] <= nums[mid]) {
23+
if (target in nums[low] .. nums[mid]) {
24+
high = mid
25+
} else {
26+
low = mid
27+
}
28+
} else {
29+
if (target in nums[mid] .. nums[high]) {
30+
low = mid
31+
} else {
32+
high = mid
33+
}
34+
}
35+
}
36+
return when (target) {
37+
nums[low] -> low
38+
nums[high] -> high
39+
else -> -1
40+
}
41+
}
42+
43+
@Test
44+
fun `배열에서 타겟의 인덱스를 반환한다`() {
45+
search(intArrayOf(4,5,6,7,0,1,2), 0) shouldBe 4
46+
search(intArrayOf(4,5,6,7,0,1,2), 3) shouldBe -1
47+
search(intArrayOf(2,3,4,5,6,0,1), 1) shouldBe 6
48+
search(intArrayOf(1,2,3,4,5,6,7), 6) shouldBe 5
49+
}
50+
}

0 commit comments

Comments
 (0)