Skip to content

Commit 73411d4

Browse files
committed
feat: add maximum depth of binary tree solution
1 parent 3be7ea5 commit 73411d4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import Optional
2+
3+
4+
# Definition for a binary tree node.
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution:
13+
def maxDepth(self, root: Optional[TreeNode]) -> int:
14+
"""
15+
- Idea: 이진 트리의 μ΅œλŒ€ κΉŠμ΄λŠ” ν˜„μž¬ λ…Έλ“œμ˜ 깊이(1)와 ν•˜μœ„ 트리의 μ΅œλŒ€ 깊이 쀑 큰 값을 λ”ν•œ κ²ƒμœΌλ‘œ μ •μ˜ν•œλ‹€.
16+
- Time Complexity: O(n). n은 전체 λ…Έλ“œμ˜ 수
17+
λͺ¨λ“  λ…Έλ“œλ₯Ό ν•œλ²ˆμ”© λ°©λ¬Έν•˜μ—¬ νƒμƒ‰ν•˜κΈ° λ•Œλ¬Έμ— O(n)이 μ†Œμš”λœλ‹€.
18+
- Space Complexity: O(n). n은 전체 λ…Έλ“œμ˜ 수
19+
μž¬κ·€μ μœΌλ‘œ 탐색할 λ•Œ, 호좜 μŠ€νƒμ— μŒ“μ΄λŠ” ν•¨μˆ˜ 호좜의 μˆ˜λŠ” μ΅œλŒ€ 트리의 κΉŠμ΄μ™€ κ°™λ‹€.
20+
νŠΈλ¦¬κ°€ 편ν–₯λ˜μ–΄ μžˆλŠ” μ΅œμ•…μ˜ 경우, κΉŠμ΄κ°€ n이 될 수 있기 λ•Œλ¬Έμ— O(n)으둜 ν‘œν˜„ν•  수 μžˆλ‹€.
21+
"""
22+
if root is None:
23+
return 0
24+
25+
left_depth = self.maxDepth(root.left)
26+
right_depth = self.maxDepth(root.right)
27+
28+
return max(left_depth, right_depth) + 1

0 commit comments

Comments
Β (0)