Readable python solution using Queue


  • 0
    L
        def averageOfLevels(self, root):
            queue = collections.deque([root])
            ret = []
            while queue:
                averageSum, levelTotal = 0, 0.0
                currentLevelNotEmpty = len(queue)
                while currentLevelNotEmpty:
                    currentLevelNotEmpty -= 1
                    levelTotal += 1
                    node = queue.popleft()
                    averageSum += node.val
                    if node.left: queue.append(node.left)
                    if node.right: queue.append(node.right)
                ret.append(averageSum/levelTotal)
            return ret
    

Log in to reply
 

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