Skip to content

Commit bb30d9f

Browse files
authored
Merge pull request #1056 from EcoFriendlyAppleSu/main
[친환경사과] week 12
2 parents f868308 + 2f2b61a commit bb30d9f

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package leetcode_study
2+
3+
/*
4+
* 끝에서 n 번째 노드를 제거하는 문제
5+
* 예외 상황이 발생하는 Case를 나눠 문제 해결
6+
* 시간 복잡도 : O(n)
7+
* -> node list를 순회하며 배열에 담는 과정
8+
* 공간 복잡도 : O(n)
9+
* -> 각 node를 담을 list 공간
10+
* */
11+
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
12+
val tempNodeList = mutableListOf<ListNode>()
13+
var currentHead = head
14+
while (currentHead != null) {
15+
tempNodeList.add(currentHead)
16+
currentHead = currentHead.next
17+
}
18+
19+
val preIndex = tempNodeList.size - n - 1
20+
val postIndex = tempNodeList.size - n + 1
21+
22+
if (preIndex < 0) {
23+
if (tempNodeList.size == 1) {
24+
return null
25+
}
26+
return tempNodeList[postIndex]
27+
} else if (postIndex == tempNodeList.size) {
28+
tempNodeList[preIndex].next = null
29+
return head
30+
} else {
31+
tempNodeList[preIndex].next = tempNodeList[postIndex]
32+
}
33+
return head
34+
}

same-tree/EcoFriendlyAppleSu.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package leetcode_study
2+
3+
/**
4+
* 같은 이진 트리 확인 문제
5+
* 재귀를 사용해 문제 해결
6+
*
7+
* 시간 복잡도: O(n)
8+
* -> 모든 노드를 방문하여 비교 진행
9+
* 공간 복잡도: O(n)
10+
* -> 재귀 호출 횟수 n 회
11+
*
12+
* 재귀 문제를 다룰 때 의식적인 연습
13+
* 1. Base Case(기저 조건)를 명확하게 정의
14+
* 2. 기저 조건으로 주어진 문제에 따라서 탈출 조건 정의
15+
* 3. 작은 문제로 나눠 생각하기
16+
* 4. 작은 문제를 결합하여 정답 도출
17+
*/
18+
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
19+
if (p == null && q == null) return true // 둘 다 null이면 같음
20+
if (p == null || q == null) return false // 한쪽만 null이면 다름
21+
if (p.`val` != q.`val`) return false // 값이 다르면 다름
22+
23+
// 왼쪽 서브트리와 오른쪽 서브트리를 각각 재귀적으로 비교
24+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
25+
}

0 commit comments

Comments
 (0)