Average of Levels in Binary Tree
Given the root of a binary tree, return an array with the average value of the nodes on each level, starting with the root's level and going down.
Answers within 10^-5 of the exact average are accepted, so ordinary floating-point division is fine. If the tree is empty, return an empty array.
Constraints
- The tree has between
0and10^4nodes. -2^31 <= Node.val <= 2^31 - 1
Examples
Example 1
Input: root = [4,7,9,10,2,null,6] Output: [4,8,6]
Level 1 is just 4. Level 2 averages (7 + 9) / 2 = 8. Level 3 averages (10 + 2 + 6) / 3 = 6.
Example 2
Input: root = [3,1,2] Output: [3,1.5]
(1 + 2) / 2 = 1.5: averages don't have to be whole numbers.
Example 3
Input: root = [] Output: []
An empty tree has no levels, so the result is an empty array.
JavaScript you'll use: Stacks, queues and deques Numbers, Math and integer tricks
/**
* Tree nodes are provided (you don't need to define them):
* class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
*/
/**
* @param {TreeNode | null} root
* @return {number[]}
*/
function averageOfLevels(root) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.