KatInterview

637. Average of Levels in Binary Tree

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to traverse a binary tree and calculate the average value of all nodes at each level. The output should be an array where each element corresponds to the average of a level.

Solution

Average of Levels in Binary Tree in Python

# 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
import collections
from typing import List, Optional

class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        if not root:
            return []
        
        result = []
        # Use a deque for efficient appends and pops from both ends.
        q = collections.deque([root])
        
        while q:
            # Get the number of nodes at the current level.
            level_size = len(q)
            # Python integers have arbitrary precision, so no overflow worries for sum.
            level_sum = 0
            
            # Process all nodes in the current level.
            for _ in range(level_size):
                node = q.popleft()
                level_sum += node.val
                
                # Add children to the queue for the next level.
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            
            # Calculate the average and add to the result list.
            result.append(level_sum / level_size)
            
        return result

Average of Levels in Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            // Get the number of nodes at the current level.
            int levelSize = q.size();
            // Use double for the sum to handle large sums and for floating point division.
            double levelSum = 0.0;

            // Process all nodes in the current level.
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = q.poll();
                levelSum += node.val;
                
                // Add children to the queue for the next level.
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
            
            // Calculate the average for the current level and add to result.
            result.add(levelSum / levelSize);
        }
        
        return result;
    }
}

Average of Levels in Binary Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <vector>
#include <queue>

class Solution {
public:
    std::vector<double> averageOfLevels(TreeNode* root) {
        std::vector<double> result;
        if (!root) {
            return result;
        }

        std::queue<TreeNode*> q;
        q.push(root);

        while (!q.empty()) {
            // Get the number of nodes at the current level.
            int level_size = q.size();
            // Use long long for the sum to prevent potential overflow.
            long long level_sum = 0; 

            // Process all nodes in the current level.
            for (int i = 0; i < level_size; ++i) {
                TreeNode* node = q.front();
                q.pop();
                level_sum += node->val;

                // Add children to the queue for the next level.
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            
            // Calculate the average for the current level and add to result.
            result.push_back(static_cast<double>(level_sum) / level_size);
        }
        
        return result;
    }
};

Average of Levels in Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function averageOfLevels(root: TreeNode | null): number[] {
    const result: number[] = [];
    if (!root) {
        return result;
    }

    // Using an array as a queue. For very large trees, a more performant queue might be better.
    const queue: TreeNode[] = [root];

    while (queue.length > 0) {
        // Get the number of nodes at the current level.
        const levelSize = queue.length;
        // JavaScript numbers are 64-bit floats, sufficient for the sum.
        let levelSum = 0;

        // Process all nodes in the current level.
        for (let i = 0; i < levelSize; i++) {
            // shift() removes the first element, simulating a queue's dequeue operation.
            // Non-null assertion `!` is safe because queue.length > 0.
            const node = queue.shift()!;
            levelSum += node.val;
            
            // Add children to the queue for the next level.
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        
        // Calculate the average for the current level and add to result.
        result.push(levelSum / levelSize);
    }
    
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.