Skip to content

Average of Levels in Binary Tree

Given the root of a binary tree, return an array of the average value of the nodes on each level of the tree.

Answers within 10^-5 of the actual answer will be accepted as correct.

InputOutputExplanation
[3,9,20,null,null,15,7][3.00000,14.50000,7.50000]Level 1: 3/1=3; Level 2: (9+20)/2=14.5; Level 3: (15+7)/2=7.5
[3,9,20][3.00000,14.50000]Level 1: 3; Level 2: (9+20)/2=14.5
Example 1: 3 Level 1: avg = 3
/ \
9 20 Level 2: avg = (9+20)/2 = 14.5
/ \
15 7 Level 3: avg = (15+7)/2 = 7.5
Example 2: 3 Level 1: avg = 3
/ \
9 20 Level 2: avg = 14.5
  • The number of nodes in the tree is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1
ApproachTimeSpaceBest When
BFS Level-OrderO(n)O(w)Clear level-by-level processing
DFS with Level TrackingO(n)O(h)Smaller trees; prefer recursion

Where h = height, w = max width

  • Pick BFS Level-Order for intuitive, clear level-by-level aggregation.
  • Pick DFS with Level Tracking if you prefer recursive solutions.
Level-by-Level
BFS Level-Order
O(n) time · O(w) space
Recursive
DFS with Level Tracking
O(n) time · O(h) space
★ Recommended

Use a queue to traverse level by level. For each level, sum all node values, then divide by the count.

⏱ Time O(n) Visit all nodes 💾 Space O(w) Queue width at widest level

Input: root = [3,9,20,null,null,15,7]

Level 1: sum=3, count=1, avg=3.0 Level 2: sum=29, count=2, avg=14.5 Level 3: sum=22, count=2, avg=7.5

function averageOfLevelsBFS(root):
result = []
queue = [root]
while queue is not empty:
levelSize = length of queue
levelSum = 0
for i = 0 to levelSize - 1:
node = queue.dequeue()
levelSum += node.val
if node.left exists:
queue.enqueue(node.left)
if node.right exists:
queue.enqueue(node.right)
result.append(levelSum / levelSize)
return result
average_of_levels_in_binary_tree_bfs.py
from typing import Optional, List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def averageOfLevels(root: Optional[TreeNode]) -> List[float]:
"""BFS level-order traversal to calculate averages."""
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
level_sum = 0
for _ in range(level_size):
node = queue.popleft()
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_sum / level_size)
return result
if __name__ == "__main__":
root1 = TreeNode(3)
root1.left = TreeNode(9)
root1.right = TreeNode(20)
root1.right.left = TreeNode(15)
root1.right.right = TreeNode(7)
result1 = averageOfLevels(root1)
print(f"Averages: {result1}") # Expected: [3.0, 14.5, 7.5]
🎯 Interview Favourite

Use DFS to traverse the tree, tracking the current level. Maintain lists of sums and counts per level, then calculate averages.

⏱ Time O(n) Visit all nodes 💾 Space O(h) Recursion call stack

DFS visits nodes in pre-order: 3 (L0), 9 (L1), 20 (L1), 15 (L2), 7 (L2)

Accumulate:

  • Level 0: sum=3, count=1
  • Level 1: sum=29, count=2
  • Level 2: sum=22, count=2

Average: [3.0, 14.5, 7.5]

function averageOfLevelsDFS(root):
sums = []
counts = []
function dfs(node, level):
if node is null:
return
if level == length of sums:
sums.append(0)
counts.append(0)
sums[level] += node.val
counts[level] += 1
dfs(node.left, level + 1)
dfs(node.right, level + 1)
dfs(root, 0)
result = []
for i in range(length of sums):
result.append(sums[i] / counts[i])
return result
average_of_levels_in_binary_tree_dfs.py
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def averageOfLevels(root: Optional[TreeNode]) -> List[float]:
"""DFS with level tracking to calculate averages."""
sums = []
counts = []
def dfs(node: Optional[TreeNode], level: int) -> None:
if not node:
return
if level == len(sums):
sums.append(0)
counts.append(0)
sums[level] += node.val
counts[level] += 1
dfs(node.left, level + 1)
dfs(node.right, level + 1)
dfs(root, 0)
return [sums[i] / counts[i] for i in range(len(sums))]
if __name__ == "__main__":
root1 = TreeNode(3)
root1.left = TreeNode(9)
root1.right = TreeNode(20)
root1.right.left = TreeNode(15)
root1.right.right = TreeNode(7)
result1 = averageOfLevels(root1)
print(f"Averages: {result1}") # Expected: [3.0, 14.5, 7.5]
🎯 Interview Favourite

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(n) Efficient space usage
function approach3():
// Implementation approach goes here
average_of_levels_in_binary_tree_bfs_iterative.py
"""
Solution for Average of Levels in Binary Tree
"""
def solve():
"""Implementation for approach 3 of Average of Levels in Binary Tree"""
pass
if __name__ == "__main__":
print("Solution ready")