Skip to main content

Average of Levels in Binary Tree

Question

What is the average value of all nodes at each level of a given Binary Tree?

Example 1
Input: 
3
/ \
9 20
/ \
15 7

Output: [3, 14.5, 11]

Solution

all//Average of Levels in Binary Tree.py


# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

class Solution:
def averageOfLevels(self, root):
if not root:
return []
result = []
queue = [root]
while queue:
size = len(queue)
level_sum = 0
for i in range(size):
node = queue.pop(0)
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_sum / size)
return result