File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ class Solution :
3+ def maxDepth (self , root : Optional ['TreeNode' ]) -> int :
4+ """
5+ 문제
6+ - 이진트리의 최대 깊이를 구하라.
7+
8+ 아이디어 (재귀 DFS)
9+ - 공집합(None)의 깊이는 0
10+ - 현재 노드 깊이 = max(왼쪽 서브트리 깊이, 오른쪽 서브트리 깊이) + 1
11+
12+ 시간복잡도: O(n) — 각 노드를 한 번씩 방문
13+ 공간복잡도: O(h) — 재귀 스택(h는 트리 높이; 최악 O(n), 평균 O(log n))
14+ """
15+ # 1) 빈 트리이면 깊이 0
16+ if not root :
17+ return 0
18+
19+ # 2) 왼쪽/오른쪽 서브트리의 최대 깊이를 구한다
20+ left_depth = self .maxDepth (root .left )
21+ right_depth = self .maxDepth (root .right )
22+
23+ # 3) 현재 노드의 깊이 = 더 큰 서브트리 깊이 + 1(현재 노드 포함)
24+ return max (left_depth , right_depth ) + 1
25+ # dfs(3) - 왼쪽으로 이동
26+ # dfs(9) - 왼쪽으로 이동
27+ # dfs(None) -> 0
28+ # dfs(9) - 오른쪽으로 이동
29+ # dfs(None) -> 0
30+ # dfs(9) 반환: max(0,0)+1 = 1
31+ # dfs(3) - 오른쪽으로 이동
32+ # dfs(20) - 왼쪽으로 이동
33+ # dfs(15) - 왼쪽으로 이동
34+ # dfs(None) -> 0
35+ # dfs(15) - 오른쪽으로 이동
36+ # dfs(None) -> 0
37+ # dfs(15) 반환: max(0,0)+1 = 1
38+ # dfs(20) - 오른쪽으로 이동
39+ # dfs(7) - 왼쪽으로 이동
40+ # dfs(None) -> 0
41+ # dfs(7) - 오른쪽으로 이동
42+ # dfs(None) -> 0
43+ # dfs(7) 반환: max(0,0)+1 = 1
44+ # dfs(20) 반환: max(1,1)+1 = 2
45+ # dfs(3) 반환: max(1,2)+1 = 3
46+ # 최종 결과: 3
You can’t perform that action at this time.
0 commit comments