Skip to content

17주차 문제 해결. #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions 잡부/17주차/이진검색트리.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
```Kotlin
import java.io.BufferedReader
import java.io.InputStreamReader

fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val nodes = mutableListOf<Int>()

while (true) {
val input = br.readLine() ?: break
nodes.add(input.toInt())
}

postOrder(nodes, 0, nodes.size - 1)
}

fun postOrder(nodes: List<Int>, start: Int, end: Int) {
if (start > end) return

val root = nodes[start]
var rightStart = end + 1

for (i in start + 1..end) {
if (nodes[i] > root) {
rightStart = i
break
}
}

postOrder(nodes, start + 1, rightStart - 1) // 왼쪽 서브트리
postOrder(nodes, rightStart, end) // 오른쪽 서브트리
println(root) // 루트 출력
}
```

현재 값보다 큰 값을 찾는다.

큰 값을 기준으로 Left / Right 가 나눠지기 때문이다.
27 changes: 27 additions & 0 deletions 잡부/17주차/이진트리의직경.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
```Kotlin
import utils.TreeNode
import kotlin.math.max

class DiameterOfBinaryTree {
private var longest:Int = 0

private fun dfs(root: TreeNode?): Int {
if (root == null) {
return -1
}

val left = dfs(root.left)
val right = dfs(root.right)

longest = max(longest, left + right + 2)
return max(right, left) + 1
}

fun diameterOfBinaryTree(root: TreeNode?): Int {
dfs(root)
return longest
}
}
```

leaf 노드로부터 leaf 노드가 가질 수 있는 최고의 길이를 구하여 활용할 수 있도록 한다.
25 changes: 25 additions & 0 deletions 잡부/17주차/이진트리의최대깊이.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
```Kotlin
class MaximumDepthOfBinaryTree {
fun recv(root: TreeNode?, depth: Int): Int {
if (root == null) return depth

var currentDepth = depth;
if (root.left != null) {
currentDepth = max(recv(root.left, depth+1), currentDepth)
}

if (root.right != null) {
currentDepth = max(recv(root.right, depth+1), currentDepth)
}

return currentDepth
}

fun maxDepth(root: TreeNode?): Int {
if (root == null) return 0
return recv(root, 1);
}
}
```

재귀를 통해서, 가장 깊이 들어갈 수 있는 값을 구한다.