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
Example 1
Output: [3.0, 14.5, 11.0]
Example 2
Output: [3.0, 14.5, 11.0]
Explanation: here 15 and 7 are children of 9, but each level holds the same values.
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
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
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
Taking off size
Adding up a level
Can the sum of one level be too big? Each node value is an intintintlonglong
Dividing with a fraction
How do we make 29 divided by 2 come out as 14.5? Dividing a longint(double) sum / sizedouble
The brackets matter here. (double) (sum / size)double
Java Solution
The method averageOfLevels
- First, create the answer list,
, and a queue namedaverages that holds the root. The queue is anqueue , a Java class that here adds at the back withArrayDeque and takes from the front withadd .poll - While
is not empty, start a new level: read the number of nodes on it intoqueue , and set asize namedlong to 0.sum - Inside, a
loop takesfor nodes off the front withsize . It adds each node's value topoll and puts the node's left and right children, when they exist, at the back ofsum .queue - After that loop, add
to(double) sum / size .averages - Once
is empty, every level has its average, and the method returnsqueue .averages
Around the method sit a small TreeNodebuild
The main
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:
[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][5.0]
Look at [1.0, 2.5, 4.5, 6.0]
The last line is the overflow check. Its second level holds two nodes of 2,147,483,647, and the longint
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.