"one-liner"


  • 2

    Well, one line in addition to copying&pasting a solution from the earlier Binary Tree Level Order Traversal problem and importing the statistics module. I just like to reuse my code.

    from statistics import mean
    
    class Solution:
    
        def averageOfLevels(self, root):
            return list(map(mean, self.levelOrder(root)))
    
        # copied&pasted from old problem's solution:
        def levelOrder(self, root):
            levels = []
            level = [root]
            while any(level):
                levels.append([node.val for node in level])
                level = [kid for node in level for kid in (node.left, node.right) if kid]
            return levels
    

    Here's a version without that help:

    def averageOfLevels(self, root):
        averages = []
        level = [root]
        while level:
            averages.append(sum(node.val for node in level) / len(level))
            level = [kid for node in level for kid in (node.left, node.right) if kid]
        return averages

  • 0
    J

    need to change to float, otherwise, python will use integer division by default


  • 0

    @JoyceZhang Not true in Python 3, which I used.


Log in to reply
 

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