104 | Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/



이상 코드
import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
queue = collections.deque([root])
depth = 0
while queue:
depth += 1
# 큐 연산 추출 노드의 자식 노드 삽입
for _ in range(len(queue)):
cur_root = queue.popleft()
if cur_root.left:
queue.append(cur_root.left)
if cur_root.right:
queue.append(cur_root.right)
# BFS 반복 횟수 == 깊이
return depth
- 반복문을 이용한 BFS
- queue를 한 번 돌 때 depth += 1 / 계속 호출되는 것이 아니라 간단했음
반응형
'Algorithm > 파이썬 알고리즘 인터뷰' 카테고리의 다른 글
| [트리] 정렬된 배열의 이진 탐색 트리 반환 (0) | 2022.05.16 |
|---|---|
| [트리] 가장 긴 동일 값의 경로 (0) | 2022.05.10 |
| [연결 리스트] 팰린드롬 연결 리스트 (0) | 2022.04.06 |
| [해시 테이블] 상위 K 빈도 요소 (0) | 2022.03.17 |
| [해시 테이블] 중복 문자 없는 가장 긴 부분 문자열 (0) | 2022.03.16 |
댓글