Average of Levels in Binary Tree

Average the node values on each level of a binary tree, walking it row by row with a queue.

Given the root of a binary tree with at least one node, return the average value of the nodes on each level, as a list from the top level down. An answer within 10-5 of the exact average is accepted. In the examples, the tree is written row by row, left to right, with null for a missing child.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [3.0, 14.5, 11.0]
Example 2
Input: root = [3, 9, 20, 15, 7]
Output: [3.0, 14.5, 11.0]
Explanation: here 15 and 7 are children of 9, but each level holds the same values.
Solution

The Idea

Think of a family tree drawn on paper: the oldest person at the top, their children on the row below, the grandchildren on the row below that. In a tree, each such row is called a level. This problem asks for one number per level: the average of the values on it.

In Example 1, the node at the top, called the root, holds 3. It has two children, 9 on the left and 20 on the right. The two null entries say that 9 has no children, and 20 has two of its own, 15 and 7. Look at the picture below.

The tree of Example 1 cut into three levels. Level 0 holds 3, average 3.0. Level 1 holds 9 and 20, sum 29 over 2 nodes, average 14.5. Level 2 holds 15 and 7, sum 22 over 2 nodes, average 11.0.

The bands labelled level 0, level 1 and level 2 cut the tree into its rows. Level 1, highlighted, holds 9 and 20: their sum is 29 over 2 nodes, so the average is 14.5. Level 2 holds 15 and 7, which gives 22 over 2 nodes, or 11.0.

Reading the levels off a picture is easy. A tree in memory has no rows, though: each node only knows its own left and right child. Starting from the root, how do we gather the nodes of one level, and know where that level ends?

We visit the tree row by row, using a waiting line of nodes. Take nodes off the front, and put each node's children at the back. All the children of level 1 join the line behind the last node of level 1, so the levels come off the front in order, top to bottom.

Visiting a tree this way, one level after another, is called breadth-first search, or BFS, and the waiting line is a queue. The same walk solves Level Order Traversal, which lists the values of each level instead of averaging them.

Solution Approach

Turning that idea into code means settling three things: how to tell where one level ends in the queue, how to add up a level without the sum going wrong, and how to divide so the average keeps its fraction.

Where a level ends

How does the loop know which nodes in the queue belong to the current level? Before taking any node off, it reads the queue's size into a variable named size. At that moment the queue holds exactly the current level: the level above is gone, and none of this level's children have been added yet.

Taking off size nodes finishes the level. The children added along the way stay in the queue and form the next level, ready for the next round.

Adding up a level

Can the sum of one level be too big? Each node value is an int, so it can be as large as 231 - 1, or 2,147,483,647, the top of the Java int range. Two such values on one level go past that top, and an int sum wraps around to -2. A long reaches about 9.2 × 1018, so a long sum has plenty of room.

Dividing with a fraction

How do we make 29 divided by 2 come out as 14.5? Dividing a long by an int in Java keeps only the whole part, so 29 / 2 is 14. Writing (double) sum / size turns the sum into a double first, so the division keeps the .5.

The brackets matter here. (double) (sum / size) divides first and turns the 14 into a double afterwards, which gives 14.0 for level 1 of Example 1.

Java Solution

The method averageOfLevels works in these steps:

  1. First, create the answer list, averages, and a queue named queue that holds the root. The queue is an ArrayDeque, a Java class that here adds at the back with add and takes from the front with poll.
  2. While queue is not empty, start a new level: read the number of nodes on it into size, and set a long named sum to 0.
  3. Inside, a for loop takes size nodes off the front with poll. It adds each node's value to sum and puts the node's left and right children, when they exist, at the back of queue.
  4. After that loop, add (double) sum / size to averages.
  5. Once queue is empty, every level has its average, and the method returns averages.

Around the method sit a small TreeNode class, with a value and links to a left and a right child, and a build helper that turns the row-by-row form of the examples into a tree.

The main method runs both examples, a single node, an uneven tree with four levels, a tree of negative values, and a level with two nodes of 2,147,483,647.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class AverageOfLevels {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<Double> averageOfLevels(TreeNode root) {
        List<Double> averages = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();          // nodes on this level
            long sum = 0;                     // values can be near the int limits
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.add(node.left);     // waits for the next level
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            averages.add((double) sum / size);
        }
        return averages;
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(averageOfLevels(build(3, 9, 20, null, null, 15, 7)));
        System.out.println(averageOfLevels(build(3, 9, 20, 15, 7)));
        System.out.println(averageOfLevels(build(5)));
        System.out.println(averageOfLevels(build(1, 2, 3, 4, null, null, 5, 6)));
        System.out.println(averageOfLevels(build(-4, -1, -2)));
        int max = Integer.MAX_VALUE;
        System.out.println(averageOfLevels(build(max, max, max)));
    }
}

Running it prints:

Output
[3.0, 14.5, 11.0]
[3.0, 14.5, 11.0]
[5.0]
[1.0, 2.5, 4.5, 6.0]
[-4.0, -1.5]
[2.147483647E9, 2.147483647E9]

Examples 1 and 2 build trees of different shapes, yet both print [3.0, 14.5, 11.0], since only the values on each level count. The single node prints [5.0], its own value.

Look at [1.0, 2.5, 4.5, 6.0]. That tree's levels hold 1, then 2 and 3, then 4 and 5, then 6 on its own, so the last level is divided by 1 node, not 2. The negative tree gives -1.5 for -1 and -2, the same way as positive values.

The last line is the overflow check. Its second level holds two nodes of 2,147,483,647, and the long sum gives 2.147483647E9, Java's way of printing 2.147483647 × 109. With an int sum instead, a separate test program printed -1.0 for that level.

Complexity

The work is one pass through the queue, plus one division per level.

  • Time: O(n), because each of the n nodes enters the queue once and leaves it once, with one addition and two child checks in between.
  • Space: O(w), where w is the largest number of nodes on one level, because the queue holds at most the rest of one level plus the children already added from it.