Skip to content

Commit 28cef36

Browse files
author
이연수
committed
same tree
1 parent cf5691a commit 28cef36

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

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)