python - min ht of a tree - ret ht of first leaf from root - 98.5%


  • 0
    S
    # 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 not root:
                return 0
            
            queue = [(root, 1)]
            length = len(queue)
            ans = []
            while length:
                # put question specific code here for BFS problems
                # get the average of the current level
                    
                # enqueue the children of the all nodes
                # in the current level
                tmpq = []
                for t in queue:
                    node = t[0]
                    if not (node.left or node.right):
                        return t[1]
                    
                    if node.left:
                        tmpq.append((node.left, t[1]+1))
                    if node.right:
                        tmpq.append((node.right, t[1]+1))
    
                # reassign the queue
                queue = tmpq
                length = len(queue)                            
                    
                
    

Log in to reply
 

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