Skip to content

Commit 5723acb

Browse files
committed
104. Maximum Depth of Binary Tree (BFS 풀이 추가)
1 parent 3e0f2b8 commit 5723acb

1 file changed

Lines changed: 45 additions & 9 deletions

File tree

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,64 @@
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-
8-
# 시간 복잡도: O(N), 모든 노드를 한번 씩 방문
9-
# 공간 복잡도: O(N), 최악의 경우 모든 노드가 큐에 담길 수 있음
1+
'''
2+
스택을 활용한 DFS
3+
4+
시간 복잡도: O(N)
5+
공간 복잡도: O(H), H: 트리의 높이
6+
'''
107
class Solution:
118
def maxDepth(self, root: Optional[TreeNode]) -> int:
9+
# 트리가 비어있으면 길이는 0
1210
if root is None:
1311
return 0
1412

1513
max_depth = 1
14+
15+
# 스택에 (현재 노드, 노드의 깊이) 튜플을 저장
1616
stack = [(root, 1)]
1717

1818
while stack:
1919
node, cur_depth = stack.pop()
20+
21+
# 현재 노드의 깊이와 저장된 최댓값을 비교하여 갱신
2022
max_depth = max(cur_depth, max_depth)
2123

24+
# 왼쪽 자식 노드가 있다면 현재 깊이 + 1을 하여 스택에 추가
2225
if node.left:
2326
stack.append((node.left, cur_depth + 1))
2427

28+
# 오른쪽 자식 노드가 있다면 현재 깊이 + 1을 하여 스택에 추가
2529
if node.right:
2630
stack.append((node.right, cur_depth + 1))
2731

2832
return max_depth
33+
34+
'''
35+
큐를 활용한 BFS
36+
37+
시간 복잡도: O(N)
38+
공간 복잡도: O(W), W: 트리의 최대 너비
39+
'''
40+
class Solution:
41+
def maxDepth(self, root: Optional[TreeNode]) -> int:
42+
# 트리가 비어있으면 길이는 0
43+
if root is None:
44+
return 0
45+
46+
queue = deque([root])
47+
depth = 0
48+
49+
while queue:
50+
# 현재 레벨에 있는 노드의 개수만큼 반복 처리
51+
level_size = len(queue)
52+
53+
for _ in range(level_size):
54+
node = queue.popleft()
55+
56+
if node.left:
57+
queue.append(node.left)
58+
if node.right:
59+
queue.append(node.right)
60+
61+
# 한 레벨의 탐색이 끝나면 깊이 증가
62+
depth += 1
63+
64+
return depth

0 commit comments

Comments
 (0)