Average of Levels in Binary Tree — LeetCode 637 Python Solution

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#637
Reading time
4 min

The problem

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.

Example

Input
root = [3,9,20,null,null,15,7]
Output
[3.00000,14.50000,11.00000]
Explanation
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        q = deque([root])
        ans = []
        while q:
            s, n = 0, len(q)
            for _ in range(n):
                root = q.popleft()
                s += root.val
                if root.left:
                    q.append(root.left)
                if root.right:
                    q.append(root.right)
            ans.append(s / n)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 637. Average of Levels in Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 637. Average of Levels in Binary Tree?
LeetCode 637. Average of Levels in Binary Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 637. Average of Levels in Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 637. Average of Levels in Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 637. Average of Levels in Binary Tree cover?
LeetCode 637. Average of Levels in Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview