Average of Levels in Binary Tree

Easy#637tree nodes

You get the root of a binary tree. For every level, from the top down, find the average of its values and return the averages as a list. Our example is the tree [5, 3, 8, 2, 6, none, 10] in level order: 5 on top, 3 and 8 below it, then 2, 6 and 10 — the answer is [5, 5.5, 6].

input
root: a binary tree of at least one node, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
The average of each level's values, from the root down.
constraints
  • 1 ≤ the number of nodes ≤ 10⁴
  • −2³¹ ≤ Node.val ≤ 2³¹ − 1
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function averageOfLevels(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.