Given the root of a binary tree, return the average value of the nodes on each level as a list, starting from the root level. Answers within 10−5 of the exact averages are accepted.
Function Signature
def average_of_levels(root: Optional[TreeNode]) -> list[float]:
Rules
-
root
is a
TreeNode
with an integer
val
and
left
and
right
children, each
None
when absent.
-
The examples write the tree as a level-order list with
None
for a missing child. Children of a missing node are not listed, and trailing
None
values are left out.
-
Level 0 is the root. The output has one entry per level, from the top level down, and each entry is the sum of that level's values divided by the number of nodes on that level.
Constraints
-
The number of nodes in the tree is between 1 and
104
.
-
-2^31 <= Node.val <= 2^31 - 1
Examples
Input: root = [3, 9, 20, None, None, 15, 7]
Output: [3.0, 14.5, 11.0]
Level 0 holds only 3. Level 1 holds 9 and 20, so its average is 29 / 2 = 14.5. Level 2 holds 15 and 7, the children of 20, so its average is 22 / 2 = 11.0.
Input: root = [3, 9, 20, 15, 7]
Output: [3.0, 14.5, 11.0]
Here 15 and 7 are the children of 9. The shape differs from the first example, but each level holds the same values, so the averages are the same.
Input: root = [7, -4, 1, 2, None, None, -9]
Output: [7.0, -1.5, -3.5]
Level 1 holds -4 and 1, which sum to -3 over two nodes. Level 2 holds 2 (the left child of -4) and -9 (the right child of 1), which sum to -7 over two nodes.