Average of Levels in Binary Tree

Easy~15 min

Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10^-5 of the actual answer will be accepted.

Each node has a val (integer value), a left child, and a right child. Children may be null.

The tree is given as a level-order array where null represents a missing node. For example, [3,9,20,null,null,15,7] represents:

      3
     / \
    9  20
      /  \
     15   7

The averages for this tree are:

  • Level 0: 3 / 1 = 3
  • Level 1: (9 + 20) / 2 = 14.5
  • Level 2: (15 + 7) / 2 = 11

Examples

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [3, 14.5, 11]
Explanation: Level 0 average is 3/1 = 3. Level 1 average is (9+20)/2 = 14.5. Level 2 average is (15+7)/2 = 11.
Example 2
Input: root = [3, 9, 20, 15, 7]
Output: [3, 14.5, 11]
Explanation: Level 0: 3. Level 1: (9+20)/2 = 14.5. Level 2: (15+7)/2 = 11.
Example 3
Input: root = [1]
Output: [1]
Explanation: A single-node tree has one level with average equal to the node value.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4]
  • -2^31 <= Node.val <= 2^31 - 1
  • Expected time complexity: O(n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run