Average of Levels in Binary Tree
EASYDescription
root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Example 2:
Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000]
Constraints:
- The number of nodes in the tree is in the range
[1, 104]. -231 <= Node.val <= 231 - 1
Approaches
Checkout 2 different approaches to solve Average of Levels in Binary Tree. Click on different approaches to view the approach and algorithm in detail.
Breadth-First Search (BFS)
This approach uses Breadth-First Search (BFS), which naturally processes the tree level by level. We use a queue to keep track of nodes to visit. For each level, we iterate through all nodes on that level, calculate their sum and count, then compute the average and add it to our result list. This is a very intuitive and direct way to solve the problem.
Algorithm
- If
rootis null, return an empty list. - Initialize a result list
averagesand aQueuewith therootnode. - Loop while the
queueis not empty: a. Get the current size of the queue,levelSize. b. InitializelevelSum = 0.0. c. LooplevelSizetimes: i. Dequeue anode. ii. Addnode.valtolevelSum. iii. Enqueuenode.leftif it's not null. iv. Enqueuenode.rightif it's not null. d. Calculate the averagelevelSum / levelSizeand add it toaverages. - Return
averages.
BFS is an iterative algorithm that is perfectly suited for problems requiring level-by-level processing. The algorithm proceeds as follows:
- Create a list
averagesto store the result. If therootis null, return an empty list. - Initialize a
Queue(e.g., aLinkedList) and add therootnode to it. - Enter a loop that continues as long as the queue is not empty. This loop processes one level of the tree in each iteration.
- Inside the loop, first, get the number of nodes currently in the queue. This value,
levelSize, represents the number of nodes at the current level. - Initialize a variable
levelSumto 0.0 to accumulate the sum of node values for the current level. - Start an inner loop that runs
levelSizetimes. In this loop, we process each node of the current level. - Dequeue a node, add its value to
levelSum, and enqueue its non-null children (left and right). - After the inner loop finishes, all nodes for the current level have been processed. Calculate the average for the level (
levelSum / levelSize) and add it to theaverageslist. - The outer loop then continues to the next level.
Once the queue is empty, all levels have been processed, and the
averageslist contains the final result.
/**
* 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> averages = new ArrayList<>();
if (root == null) {
return averages;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
double levelSum = 0.0;
for (int i = 0; i < levelSize; i++) {
TreeNode currentNode = queue.poll();
levelSum += currentNode.val;
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
averages.add(levelSum / levelSize);
}
return averages;
}
}
Complexity Analysis
Pros and Cons
- Very intuitive and direct for level-order problems.
- Processes one level completely before moving to the next.
- Can be less space-efficient than DFS, especially for balanced or "wide" trees where the maximum width W can be large (up to O(N)).
Code Solutions
Checking out 4 solutions in different languages for Average of Levels in Binary Tree. Click on different languages to view the code.
/** * 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; * } * } */ class Solution { public List < Double > averageOfLevels ( TreeNode root ) { List < Double > ans = new ArrayList <>(); Deque < TreeNode > q = new ArrayDeque <>(); q . offer ( root ); while (! q . isEmpty ()) { int n = q . size (); long s = 0 ; for ( int i = 0 ; i < n ; ++ i ) { root = q . pollFirst (); s += root . val ; if ( root . left != null ) { q . offer ( root . left ); } if ( root . right != null ) { q . offer ( root . right ); } } ans . add ( s * 1.0 / n ); } return ans ; } }Video Solution
Watch the video walkthrough for Average of Levels in Binary Tree
Similar Questions
5 related questions you might find useful
Algorithms:
Data Structures:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.