Skip to content

Average of Levels in Binary Tree

EasyTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

[5, 1, 8, 2, 3]          →  [5.0, 4.5, 2.5]
[2, -2, 4, 7, 7, -1, 0]  →  [2.0, 1.0, 3.25]
[1]                      →  [1.0]

Constraints

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