Difficulty: 🟢 Easy
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.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
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].
Example 2:
Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]
- The number of nodes in the tree is in the range
[1, 104]
. 231 <= Node.val <= 231 - 1
Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
result, level = [], [root]
while level:
result.append(sum([node.val for node in level])/len(level))
level = [node.left for node in level if node.left] + [node.right for node in level if node.right]
return result
The given solution provides an iterative approach to find the average value of nodes on each level of a binary tree.
Here is a step-by-step overview of the solution:
- Initialize an empty list
result
to store the average values of each level. - Initialize a list
level
with the root node. - Enter a loop that continues until there are no nodes left in the level:
- Calculate the average value of the nodes in the current level by summing up the values of the nodes and dividing by the number of nodes.
- Append the average value to the
result
. - Create a new list
next_level
to store the nodes of the next level. - Iterate through the nodes in the current level and add their left and right children (if they exist) to the
next_level
.
- Set the
level
to be thenext_level
for the next iteration. - Return the
result
, which contains the average values of each level.
The time complexity for this solution is O(n), where n is the number of nodes in the binary tree. We visit each node once.
The space complexity is O(m), where m is the maximum number of nodes at any level. In the worst case, the maximum number of nodes at any level can be n/2, so the space complexity is O(n/2), which simplifies to O(n).
The given solution provides an iterative approach to find the average value of nodes on each level of a binary tree. It uses a queue-like approach to traverse the tree level by level and calculate the average values. The solution has a time complexity of O(n) and a space complexity of O(m), where n is the number of nodes and m is the maximum number of nodes at any level in the binary tree.
NB: If you want to get community points please suggest solutions in other languages as merge requests.