Leetcode 104. Maximum Depth of Binary Tree
2021. 2. 8. 11:20ㆍProblem Solving/LeetCode
Leetcode 104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Logic
처음엔 보통 bfs 처럼 while
문을 돌고 depth를 하나씩 늘려줬는데
while queue:
depth += 1
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
이렇게 하면 depth가 노드갯수만큼 증가하게 된다.(당연하지만.)
따라서 원래의 while문 아래에 for문을 추가해 새로운 레벨로 들어갔을때만 depth가 증가하게 해준다.
Solution
import collections
# 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: TreeNode) -> int:
# 예외 처리
if root is None:
return 0
queue = collections.deque([root])
depth = 0
while queue:
depth += 1
for _ in range(len(queue)):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return depth
Reference
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Leetcode 46. Permutations (0) | 2021.01.29 |
---|---|
[Leetcode] 347. Top K Frequent Elements (0) | 2021.01.26 |
[Leetcode] 771. Jewels and Stones (0) | 2021.01.19 |
[Leetcode] 706. Design HashMap (0) | 2021.01.19 |
[Leetcode] 641. Design Circular Deque (0) | 2021.01.19 |