Short Python Solution using ListComprehension

  • 0
    def averageOfLevels(self, root):
            :type root: TreeNode
            :rtype: List[float]
            nodes = [root]
            ret = []
            while nodes:
                total = sum([node.val for node in nodes])
                ret.append(total / (1.0 * len(nodes)))
                nodes = [kid for node in nodes for kid in (node.left, node.right) if kid]
            return ret

Log in to reply

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