Today, we will solve the 5th problem of the March LeetCoding Challenge.
Problem Statement
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
**Input:**
3
/ \
9 20
/ \
15 7
**Output:** [3, 14.5, 11]
**Explanation:**
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Solution
According to the question, we have to find the average of each level in a binary tree. We can think about this problem as a Level Order Traversal problem. Read more about Level Order Traversal here.
Let's try to visualize the problem. So when we do the level order traversal, we will find the average of each level. This seems simple right? Let’s go through the code once.
We have levels list to keep the level sums. We use a queue to-do the Level-Order-Traversal. We first check the size of the queue, this size denotes the number of nodes in a particular level of a binary tree. We add all the values of the nodes and find their average and store it in the list. At last, we return the list.
Check out the repository.
Top comments (0)