Skip to content
Decoder

Average of Levels in Binary Tree

Easy

Problem

Given the root of a binary tree, return the average value of the nodes on each level, as a list from the top level down. Answers within 10^-5 of the exact value are accepted.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[5, 1, 8, 2, 3]
Output
[5.0, 4.5, 2.5]

Example 2

Input
[2, -2, 4, 7, 7, -1, 0]
Output
[2.0, 1.0, 3.25]

Example 3

Input
[1]
Output
[1.0]

Constraints

  • 1 <= number of nodes <= 10^4
  • -2^31 <= Node.val <= 2^31 - 1

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.