InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Average of Levels in Binary Tree

easy Original ↗ 00:00

Problem

You are given the root of a binary tree. For every depth level of the tree (the root is level 0, its children level 1, and so on), compute the average of all node values on that level. Return the averages as a list ordered from the top level down.

Answers within 10^-5 of the true average are accepted, so ordinary floating-point division is fine.

Examples

Example 1

Input:  root = [3,9,20,null,null,15,7]

        3
       / \
      9  20
        /  \
       15   7

Output: [3.0, 14.5, 11.0]

Level 0 is just 3; level 1 averages (9+20)/2 = 14.5; level 2 averages (15+7)/2 = 11.0.

Example 2

Input:  root = [1,2,3,4]
Output: [1.0, 2.5, 4.0]

Level 2 contains only the node 4, so its average is 4.0.

Constraints

  • The number of nodes is in [1, 10^4] — an O(n) traversal is expected.
  • -2^31 <= Node.val <= 2^31 - 1 — level sums can exceed 32-bit range, but Python ints don’t overflow.

Think about it first

Hint 1 The answer is organized by level. Which traversal naturally visits a tree one level at a time?
Hint 2 With a queue, everything currently in the queue at the start of a round is exactly one level. Snapshot its length before you start popping.
Hint 3 Alternatively, do a DFS carrying the current depth, and accumulate `sums[depth]` and `counts[depth]` in two lists; divide at the end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug