Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
28 changes: 28 additions & 0 deletions maximum-depth-of-binary-tree/EcoFriendlyAppleSu.kt
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오.... dfs에서 return시 depth - 1 이 상당히 참신하고 좋은것 같습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package leetcode_study

/*
* 이진 트리의 최대 깊이를 구하는 문제
* 재귀를 사용해 문제 해결
* 시간 복잡도: O(n)
* -> 이진 트리의 모든 노드를 방문
* 공간 복잡도: O(n) 혹은 O(log n)
* -> findDepth() 함수는 재귀적으로 호출되어 콜 스택에 쌓임
* -> 균형잡힌 이진트리의 경우 재귀의 깊이는 O(log n) 소요
* -> 편향된 이진트리의 경우 재귀의 깊이는 O(n) 소요
* */
fun maxDepth(root: TreeNode?): Int {
if (root == null) return 0
val maxValue = findDepth(root, 1) // 시작 깊이 값은 `1`
return maxValue
}

fun findDepth(currentNode: TreeNode?, depth: Int): Int{
// escape condition
if (currentNode == null) {
return depth - 1
}

val leftValue = findDepth(currentNode.left, depth + 1)
val rightValue = findDepth(currentNode.right, depth + 1)
return maxOf(leftValue, rightValue)
}
36 changes: 36 additions & 0 deletions reorder-list/EcoFriendlyAppleSu.kt
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제 풀이 방법에 투 포인터를 사용하신게 참신하네요!
해당 문제는 LinkedList 를 적극적으로 활용하는 문제라고 생각이 됩니다!
공간 복잡도를 O(1) 으로 풀이 하실 수 있을거에요.
도전 해 보시면 좋을것 같습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package leetcode_study

/*
* singly linked list를 재정렬하는 문제
* 시간 복잡도: O(n)
* -> 전체 노드를 저장하기 위해 순환하는 과정 O(n)
* -> 리스트의 앞과 뒤에 포인터를 두고 주소값을 변경하는 과정 O(log n)
* 공간 복잡도: O(n)
* -> 노드 전체를 담을 새로운 list 필요 O(n)
* */
fun reorderList(head: ListNode?): Unit {
val tempNodeList = mutableListOf<ListNode>()
var currentNode = head

while (currentNode != null) {
tempNodeList.add(currentNode)
currentNode = currentNode.next
}

// 양쪽 끝에서부터 교차로 연결
var i = 0
var j = tempNodeList.size - 1
while (i < j) {
// 먼저 앞쪽 노드의 next가 뒤쪽 노드를 가리키게 함
tempNodeList[i].next = tempNodeList[j]
i++ // 다음 앞쪽 노드 선택

// 만약 앞쪽과 뒤쪽이 만난 경우 (짝수개일 때), 반복 종료
if (i == j) break

// 뒤쪽 노드의 next가 새로운 앞쪽 노드를 가리키게 함
tempNodeList[j].next = tempNodeList[i]
j-- // 다음 뒤쪽 노드 선택
}
tempNodeList[i].next = null
}