my Python solution (BFS and DFS)


  • 0
    B

    #BFS
    class Solution(object):
    def minDepth(self, root):

        if root is None:
            return 0
        depth = 0
        q = []
        q.append(root)
        while q is not None:
            depth +=1
            tmp = []
            for tmpq in q:
                if tmpq.left is not None:
                    tmp.append(tmpq.left)
                if tmpq.right  is not  None:
                    tmp.append(tmpq.right)
                if tmpq.left is None and tmpq.right is None:
                    return  depth
            q = tmp
    

    DFS

    class Solution(object):
    def minDepth(self, root):

        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 1
        return self.preOrder(root,0)
    
    
    def preOrder(self,root,depth):
        if root is None:
            return
        if root.left is None and root.right is None:
            return depth+1
    
        lDepth = self.preOrder(root.left,depth)
        rDepth = self.preOrder(root.right,depth)
        if lDepth is not None and rDepth is None:
            return lDepth +1
        elif lDepth is None and rDepth is not None:
            return  rDepth +1
        else:
            return (lDepth if lDepth < rDepth else rDepth) +1

Log in to reply
 

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