DFS and BFS python solution


  • 0

    DFS

    class Solution(object):
        def search(self, root, depth=0):
            depth += 1
    
            if not root.left and not root.right:
                self.min = depth if self.min is None else min(self.min, depth)
                return
    
            if root.left:
                self.search(root.left, depth)
    
            if root.right:
                self.search(root.right, depth)
    
        def minDepth(self, root):
            if not root:
                return 0
    
            self.min = None
            self.search(root)
            return self.min
    

    BFS

    class Solution(object):
        def minDepth(self, root):
            if not root:
                return 0
    
            queue, level = [root], 1
            while queue:
                for i in xrange(len(queue)):
                    node = queue.pop(0)
    
                    if not node.left and not node.right:
                        return level
    
                    if node.left:
                        queue.append(node.left)
    
                    if node.right:
                        queue.append(node.right)
    
                level += 1

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.