Python code using level search


  • 0
    H

    We can find the first leaf using level search.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def minDepth(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root == None: return 0
            depth, cur_level = 0, [root]
            # level search
            while cur_level:
                depth += 1
                next_level = []
                for x in cur_level:
                    if x.left==None and x.right==None:  return depth
                    if x.left!=None:    next_level.append(x.left)
                    if x.right!=None:   next_level.append(x.right)
                cur_level = next_level
            return depth
    

Log in to reply
 

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