Leetcode 111. Minimum Depth of Binary Tree

Mingyu Jeon·2020년 4월 29일
0
post-thumbnail

# 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:
        if not root: return 0
        if not root.left and not root.right: return 1

        depth = 1
        q = [root, None]
        minDepth = float(inf)
        
        while q:
            node = q.pop(0)
            
            if node is None:
                depth += 1
                
                if q: q.append(None)

            else:
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                if not node.left and not node.right:
                    minDepth = min(minDepth, depth)
                    
        return minDepth

https://leetcode.com/problems/minimum-depth-of-binary-tree/

0개의 댓글