반응형
# Problem
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. ![]() ![]() Constraints:
|
# My Answer
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def dfs(r):
depth=0
if r.left is None and r.right is None:
return depth
elif r.left and r.right is None:
depth+= dfs(r.left)
elif r.right and r.left is None:
depth+=dfs(r.right)
else:
depth+=max(dfs(r.left),dfs(r.right))
depth+=1
return depth
if root is None:
return 0
depth= dfs(root)+1
return depth
# Solution 1 - 반복 구조로 BFS 풀이
import collections
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
for 문에서 부모노드의 길이 만큼만 반복
부모 노드가 모두 추출된 이후 다시 while문을 통해 다음 깊이의 노드 반복
BFS에서는 while문의 반복 횟수가 높이
반응형
'Algorithm > LEET CODE ( 파이썬 알고리즘 인터뷰)' 카테고리의 다른 글
❗️[LEET CODE] 687. Longest Univalue Path (0) | 2021.04.20 |
---|---|
[LEET CODE] 543. Diameter of Binary Tree (0) | 2021.04.19 |
[LEET CODE] 787. Cheapest Flights Within K Stops ( 다익스트라 알고리즘 ) (0) | 2021.04.14 |
[LEET CODE] 743. Network Delay Time ( 다익스트라 알고리즘) (0) | 2021.04.14 |
❗️[LEET CODE] 207. Course Schedule (0) | 2021.04.10 |