Python solution with Breadth-first Search


  • 0
    X

    class Solution(object):
    def minDepth(self, root):
    """
    :type root: TreeNode
    :rtype: int
    """
    if not root:
    return 0
    depth = 1
    now_layer = [root]

        while True:                                                              
            next_layer = []                                                      
            for leaf in now_layer:  
                if leaf is None:
                    continue
                left_child = leaf.left                                           
                right_child = leaf.right
                if left_child is None and right_child is None:  
                    return depth    
                next_layer.append(left_child)                                    
                next_layer.append(right_child)                                   
                                                            
            depth = depth+1                                                      
                                                    
            now_layer = next_layer

Log in to reply
 

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