Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

637. Average of Levels in Binary Tree

Explanation

To solve this problem, we can perform a level order traversal of the binary tree while calculating the average value of nodes at each level. We will maintain a queue to keep track of nodes at each level and a separate list to store the average values. At each level, we calculate the average value by summing up the values of nodes at that level and dividing by the number of nodes at that level.

Algorithm:

  1. Initialize a queue to store nodes at each level and a list to store average values.
  2. Push the root node into the queue.
  3. While the queue is not empty, do the following:
    • Initialize variables sum and count to calculate the sum and number of nodes at the current level.
    • Iterate through the nodes at the current level:
      • Pop a node from the queue.
      • Update sum with the node's value.
      • Increment count by 1.
      • Push the node's children into the queue if they exist.
    • Calculate the average value for the current level and add it to the list of average values.
  4. Return the list of average values.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree.

Space Complexity:

The space complexity of this algorithm is O(n) as we are using a queue to perform the level order traversal.

import java.util.*;

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

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            result.add(sum / size);
        }

        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.