본문 바로가기

Algorithm/LeetCode

[LeetCode][Python3] 111. Minimum Depth of Binary Tree

반응형
# 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.
반응형