https://leetcode.com/problems/maximum-depth-of-binary-tree/
Maximum Depth of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
이진 트리의 최대 깊이를 구하는 문제이다.
트리도 (사이클이 없는) 그래프이므로 BFS, DFS등으로 모두 순회할 수 있다. 깊이는 BFS로 트리를 순회해주면 구할 수 있다.
소스 코드
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
Q = collections.deque([root])
depth = 0
while Q:
depth += 1
for _ in range(len(Q)):
cur_root = Q.popleft()
if cur_root.left:
Q.append(cur_root.left)
if cur_root.right:
Q.append(cur_root.right)
return depth
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 687. Longest Univalue Path [Python] (0) | 2022.08.29 |
---|---|
LeetCode - 543. Diameter of Binary Tree [Python] (0) | 2022.08.28 |
LeetCode - 743. Network Delay Time [Python] (0) | 2022.08.26 |
LeetCode - 207. Course Schedule [Python] (0) | 2022.08.25 |
LeetCode - 332. Reconstruct Itinerary [Python] (0) | 2022.08.21 |