6/22/2020

[LeetCode] 111. Minimum Depth of Binary Tree

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

DFS solution:


# 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 root.left and root.right:
            return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
        
        if root.left:
            return self.minDepth(root.left) + 1
        
        if root.right:
            return self.minDepth(root.right) + 1
        
        return 1

BFS Solution:


# 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:
        
        level = 0
        queue = deque([root]) if root else deque()
        
        while queue:
            tmp = deque()
            level += 1
            while queue:
                node = queue.popleft()
                
                if not node.left and not node.right:
                    return level
                
                if node.left:
                    tmp.append(node.left)
                
                if node.right:
                    tmp.append(node.right)
            
            queue = tmp
        
        return level

No comments:

Post a Comment