반응형
# 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 minDepth(self, root: TreeNode) -> int:
queue = []
if not root: return 0
depth = 1
queue.append(root)
while(len(queue)!=0):
for _ in range(0,len(queue)):
node = queue.pop(0)
if not node.left and not node.right: return depth
elif not node.left: queue.append(node.right)
elif not node.right: queue.append(node.left)
else: queue.extend([node.left,node.right])
depth+=1
bfs로 검색을 하다 자식 노드가 없는 노드를 발견하면 해당 노드의 깊이를 return 하도록 했다.
Runtime: 464 ms, faster than 95.93% of Python3 online submissions for Minimum Depth of Binary Tree.
Memory Usage: 48.9 MB, less than 97.73% of Python3 online submissions for Minimum Depth of Binary Tree.
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 130. Surrounded Regions (0) | 2021.01.01 |
---|---|
[LeetCode][Python3] 116. Populating Next Right Pointers in Each Node (0) | 2020.12.31 |
[LeetCode][Python3] 107. Binary Tree Level Order Traversal II (0) | 2020.12.31 |
[LeetCode][Python3] 103. Binary Tree Zigzag Level Order Traversal (0) | 2020.12.31 |
[LeetCode][Python3] 104. Maximum Depth of Binary Tree (0) | 2020.12.28 |