Average of Levels in Binary Tree
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,nullfor 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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more breadth-first search (bfs) problems
- 102Binary Tree Level Order TraversalMediumsolve
- 199Binary Tree Right Side ViewMediumsolve
- 994Rotting OrangesMediumsolve
- 1091Shortest Path in Binary MatrixMedium
- 841Keys and RoomsMediumsolve
- 117Populating Next Right Pointers in Each Node IIMediumsolve
- 103Binary Tree Zigzag Level Order TraversalMediumsolve
- 909Snakes and LaddersMediumsolve
- 433Minimum Genetic MutationMediumsolve
- 127Word LadderHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.