oneby7

Binary Trees Breadth first: level by level

375. Average of Levels in Binary Tree

Easy

You are given root, the root node of a binary tree. For each level of the tree, calculate the average of the values on that level: their sum divided by the number of nodes on the level. Return the averages as a list, from the top level down.

The root is the only node on the first level. Its children make up the second level, their children the third, and so on. Only nodes that exist count. A missing child adds nothing to the sum or to the count.

An average is a floating-point number, and correct ways of calculating it can differ in the last digits. So an average counts as right when it is within 10−5 of the exact one, or, for an average larger than 1 in absolute value, within 10−5 times it. The output writes each average with five digits after the point, as in 2.50000.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

35968-40

Input: root = [6, 9, -4, 3, null, 8, 0, null, 5]

Output: [6.00000,2.50000,3.66667,5.00000]

Explanation: 6 is alone on the first level. The second level is 9 and −4, and (9 + (−4)) / 2 = 2.5. The third level is 3, 8 and 0, and 11 / 3 = 3.66667 to five digits. The last level is 5 alone.

Example 2

-8-2-31

Input: root = [-3, -8, 1, null, -2]

Output: [-3.00000,-3.50000,-2.00000]

Explanation: The second level is −8 and 1. Their sum is −7, and −7 / 2 = −3.5. The average keeps its fraction; it is not rounded to a whole number.

Example 3

10⁹10⁹10⁹10⁹10⁹10⁹0

Input: root = [1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 0]

Output: [1000000000.00000,1000000000.00000,750000000.00000]

Explanation: The last level holds three nodes of 109 and one 0. Their sum is 3 · 109, and divided by 4 that is 750000000.

Check your understanding

Work out the answer for this input before you write any code.

root = [3, 4, 9, 2, 7, null, 6]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.