Average of Levels in Binary Tree

1 minute read

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Question

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example:

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].

Analyzation

Queue

Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use BFS algorithm to do it.

IMPORTANT PATTERN!!

All binary tree problem that relates to “LEVEL” or “DEPTH” can use this pattern.

Import a deque package and use the queue structure. (Only 1 queue & BFS algorithm) See the code below.

The Code

from collections import deque
class Solution:
    """
    @param root: the binary tree of the  root
    @return: return a list of double
    """
    def averageOfLevels(self, root):
        # write your code here
        if root is None:
            return []
            
        queue = deque([root])
        result_list = []
        
        while queue:
            level = []
            for _ in range(len(queue)):
                node = queue.popleft()
                level.append(node.val)
                
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
            result_list.append(level)
            
        ans = []
        for l in result_list:
            ans.append(float(sum(l) / len(l)))
        
        return ans

Time & Space Complexity

  • Time complexity: O(n). Remember that the best case of a Binary Tree is O(logn) since it is a balanced tree but the worst case is O(n) because it can skew to only one side.
  • Space complexity: O(n). Remember that the space complexity is always about how many nodes there are in a Binary Tree. If the tree is well-balanced then it is O(logn) but the worst case will be O(n).