InterviewPrepKit

Home / Coding / Trees

Average of Levels in Binary Tree

easy Original ↗
Solving tips
  • Answer is grouped by level, so reach for BFS: a queue naturally visits the tree one level at a time.
  • Snapshot size = len(queue) at the top of each round before popping, so you process exactly one level and enqueue exactly the next.
  • Alternative single pass: DFS carrying depth, accumulating sums[depth] and counts[depth] in two lists, then divide at the end (O(h) space vs BFS's O(w)).
  • Target O(n) time; in fixed-width languages a wide level can overflow a 32-bit sum, so use a 64-bit accumulator (Python ints are immune).

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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.