Skip to content

Average of Levels in Binary Tree

Return the average value of each level of a binary tree, processing the BFS queue one level at a time.

EasyTree BFS
Solve on LeetCode

The problem

You get the root of a binary tree. Return a list with the average value of the nodes on each level, from the root's level down. Answers within 10^-5 of the exact average are accepted.

Input root = [4, 9, 6, null, null, 3, 8]

Output [4.0, 7.5, 5.5]

The second level holds 9 and 6, so its average is 7.5; the third holds 3 and 8, which gives 5.5.

Input root = [2147483647, 2147483647, 2147483647]

Output [2147483647.0, 2147483647.0]

The two values on the second level add up to more than a 32-bit int can hold, so the sum needs a wider type.

Key constraint: Node values can be as large as 2^31 - 1, so adding up a level in a 32-bit int can overflow.

How to spot the pattern

  • The answer has one value per level of the tree.
  • You need all the nodes of a level together, which is exactly what breadth-first search gives you.

The idea

Breadth-first search visits the tree level by level when you process the queue in batches. At the start of each batch the queue holds exactly the nodes of one level, so note its size, pop that many nodes, add up their values and push their children for the next level. The level's average is that sum divided by the size.

Brute force: Find the height, then for every level walk the tree from the root to collect that level's nodes, which takes O(n * h) time.

Step by step

  1. 1If the root is null, return an empty list; otherwise put the root in a queue.
  2. 2While the queue is not empty, read size, the number of nodes in it: that is exactly one level.
  3. 3Pop size nodes, add their values to a sum kept in a 64-bit integer, and push their non-null children.
  4. 4Append sum / size, using floating-point division, and continue with the next level.

See the pattern move

The tree bfs pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        if root is None:
            return []
        averages = []
        queue = deque([root])
        while queue:
            size = len(queue)  # the queue holds exactly one level right now
            total = 0
            for _ in range(size):
                node = queue.popleft()
                total += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            averages.append(total / size)
        return averages

Complexity

Time

O(n)

Space

O(w)

Each node is pushed and popped once; w is the largest number of nodes on one level, which the queue never holds much more than (up to about n / 2).

Watch out for

  • Summing in a 32-bit int: two values of 2^31 - 1 already overflow it.
  • Integer division when computing the average, which turns 7.5 into 7.
  • Using the queue's length while you are pushing children, which mixes two levels; read the size once before the batch.

Follow-up questions

Can you do it with DFS instead?

Yes: pass the depth down the recursion and keep a sum and a count per depth in two lists, then divide them at the end. It uses O(h) stack space instead of the queue.

What if you need the largest value of each level instead?

Use the same loop and keep a running maximum during each level's batch instead of a sum.

In Hinglish

Queue mein ek waqt par ek hi level ke nodes hote hain: pehle size note karo, utne nodes nikaalo, unka sum karo aur bacchon ko queue mein daalo. Sum bade type mein rakhna.

Related problems