Average of Levels in Binary Tree | LeetCode 637 | Python | Solution

Click here to see the problem details on LeetCode.

Pretty simple Binary Tree problem. We can solve this using the Level Order Traversal algorithm. This way, we traverse a tree level by level. After each level completion, we calculate the average of all node values of that level. And then, it will be appended in an array for the final result. ‚ÄčThe formula to find out the average is:

sum of all the values / total nodes

Look at the following solution in Python. It will give you a better understanding.

class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        
        if root is None:
            return []
        
        result = []
        queue = [root]
        
        while queue:
            size = len(queue)
            level = []
            
            for i in range(size):
                node = queue.pop()
                level.append(node.val)
                
                if node.left:
                    queue.insert(0, node.left)
                if node.right:
                    queue.insert(0, node.right)
            
            result.append(sum(level) / len(level))
        
        return result

I hope this one will help you.