"one-liner"


  • 4

    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.


  • 0

    I think your code really reveals the power of python. I learned something from it. Thank you.

    Here is my 'java' style python code using DFS.

    class Solution:
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            
            levels = []
            def traverse(root, lvl):
                if not root: return
                if len(levels) == lvl:
                    levels.append([])
                levels[lvl].append(root.val)
                traverse(root.left, lvl+1)
                traverse(root.right, lvl+1)
            
            traverse(root, 0)
            return [sum(l)/len(l) for l in levels]
    

Log in to reply
 

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