Binary Trees Breadth first: level by level
375. Average of Levels in Binary Tree
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
Input: root = [6, 9, -4, 3, null, 8, 0, null, 5]
[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
Input: root = [-3, -8, 1, null, -2]
[-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
Input: root = [1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 1000000000, 0]
[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.
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.