Skip to content

Commit 8e26447

Browse files
committed
feat: maximum-depth-of-binary-tree 풀이 추가
1 parent d8243fe commit 8e26447

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def maxDepth(self, root: Optional[TreeNode]) -> int:
9+
if not root:
10+
return 0
11+
12+
left_depth = self.maxDepth(root.left)
13+
right_depth = self.maxDepth(root.right)
14+
15+
return max(left_depth, right_depth) + 1
16+
17+
"""
18+
================================================================================
19+
풀이 과정
20+
================================================================================
21+
22+
[1차 시도] 재귀로 깊이 카운트 - None은 0
23+
────────────────────────────────────────────────────────────────────────────────
24+
1. 빈 노드(None)는 깊이가 0이
25+
2. leaf 노드에서 양쪽 자식이 None이면 둘 다 0을 반환
26+
3. 그러면 leaf 노드는 max(0, 0) + 1 = 1이 됨 (자기 자신만 카운트)
27+
28+
def maxDepth(self, root):
29+
if not root:
30+
return 0 # 빈 노드는 0
31+
32+
left = self.maxDepth(root.left)
33+
right = self.maxDepth(root.right)
34+
35+
return max(left, right) + 1 # 더 깊은 쪽 + 나 자신(1)
36+
37+
4. 동작 예시:
38+
트리: 1
39+
/ \
40+
2 3
41+
/
42+
4
43+
44+
maxDepth(4) → max(0, 0) + 1 = 1
45+
maxDepth(2) → max(1, 0) + 1 = 2
46+
maxDepth(3) → max(0, 0) + 1 = 1
47+
maxDepth(1) → max(2, 1) + 1 = 3 ✓
48+
49+
50+
5. 시간복잡도: O(n) - 모든 노드를 1번씩 방문
51+
6. 공간복잡도: O(h) - 재귀 스택, h는 트리 높이
52+
"""

0 commit comments

Comments
 (0)