Straightforward python solution


  • 0
    F
    def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            queue = [root]
            ans = []
            while queue:
                next_queue = []
                cur_sum = 0
                for node in queue:
                    cur_sum += node.val
                    if node.left: next_queue.append(node.left)
                    if node.right: next_queue.append(node.right)
                ans.append(1.0 * cur_sum / len(queue))
                queue = next_queue
            return ans
    

Log in to reply
 

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