Skip to content

Practice Average of Levels in Binary Tree

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#637
LeetCode Problem

Average of Levels in Binary Tree

Problem Statement

For each depth of the binary tree rooted at root, calculate the arithmetic mean of the node values at that depth. Return the means from the root level downward. A numerical error of at most 10^-5 is accepted. Practice approach: Use a queue and freeze its size at the start of each level. Sum exactly that many nodes, enqueue their children, and divide by the saved count. Use a sufficiently wide sum and floating-point division. Every node is visited once: O(n) time and O(w) queue space for maximum level width w.

Source: Average of Levels in Binary Tree on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
root = [3,9,20,null,null,15,7]
Output
[3.00000,14.50000,11.00000]

# Example 2

Input
root = [3,9,20,15,7]
Output
[3.00000,14.50000,11.00000]

Constraints

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

Related LeetCode Problems

Practice more problems similar to Average of Levels in Binary Tree.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.