Logo
Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Solution: Level Averages in a Binary Tree

Problem Statement

Given a binary tree, populate an array to represent the averages of all of its levels.

Example 1:

Example 2:

Constraints:

  • The number of nodes in the tree is in the range [1, 10<sup>4</sup>].
  • -2<sup>31</sup> <= Node.val <= 2<sup>31</sup> - 1

Solution

This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that instead of keeping track of all nodes of a level, we will only track the running sum of the values of all nodes in each level

.....

.....

.....

Like the course? Get enrolled and start learning!