# Leetcode 637. Average of Levels in Binary Tree

### Question

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

`Input:    3   / \  9  20    /  \   15   7Output: [3, 14.5, 11]Explanation:The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].`

Note:

1. The range of node’s value is in the range of 32-bit signed integer.

### Solution

BFS travel and caculate the answer

Runtime: 82 ms

`# Definition for a binary tree node.# class TreeNode#     attr_accessor :val, :left, :right#     def initialize(val)#         @val = val#         @left, @right = nil, nil#     end# end`
`# @param {TreeNode} root# @return {Float[]}def average_of_levels(root)    queue = []    res = []        queue.push root    res.push root.val    while !queue.empty?        buf = []        queue.each do |q|            buf.push q.left if q.left            buf.push q.right if q.right        end        queue = buf        sum = 0        buf.each do |b|           sum += b.val        end        res.push sum.to_f/buf.count if buf.count != 0    end    resend`
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.