Given a non-empty binary tree, print the average value of the nodes on each level.
Examples:
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : [4 5.5 5]
The average value of nodes on level 0 is 4,
on level 1 is 5.5, and on level 2 is 5.
Hence, print [4 5.5 5].
The idea is based on Level order traversal line by line | Set 2 (Using Two Queues)
- Start by pushing the root node into the queue. Then, remove a node from the front of the queue.
- For every node removed from the queue, push all its children into a new temporary queue.
- Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty.
- Every time queue becomes empty, it indicates that one level of the tree has been considered.
- While pushing the nodes into temporary queue, keep a track of the sum of the nodes along with the number of nodes pushed and find out the average of the nodes on each level by making use of these sum and count values.
- After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node* left, *right;
};
void averageOfLevels(Node* root)
{
vector< float > res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int sum = 0, count = 0;
queue<Node*> temp;
while (!q.empty()) {
Node* n = q.front();
q.pop();
sum += n->val;
count++;
if (n->left != NULL)
temp.push(n->left);
if (n->right != NULL)
temp.push(n->right);
}
q = temp;
cout << (sum * 1.0 / count) << " " ;
}
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
averageOfLevels(root);
return 0;
}
|
Java
import java.util.*;
class GfG {
static class Node {
int val;
Node left, right;
}
static void averageOfLevels(Node root)
{
Queue<Node> q = new LinkedList<Node> ();
q.add(root);
int sum = 0 , count = 0 ;
while (!q.isEmpty()) {
sum = 0 ;
count = 0 ;
Queue<Node> temp = new LinkedList<Node> ();
while (!q.isEmpty()) {
Node n = q.peek();
q.remove();
sum += n.val;
count++;
if (n.left != null )
temp.add(n.left);
if (n.right != null )
temp.add(n.right);
}
q = temp;
System.out.print((sum * 1.0 / count) + " " );
}
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static void main(String[] args)
{
Node root = null ;
root = newNode( 4 );
root.left = newNode( 2 );
root.right = newNode( 9 );
root.left.left = newNode( 3 );
root.left.right = newNode( 5 );
root.right.right = newNode( 7 );
System.out.println( "Averages of levels : " );
System.out.print( "[" );
averageOfLevels(root);
System.out.println( "]" );
}
}
|
Python3
from queue import Queue
class newNode:
def __init__( self , data):
self .val = data
self .left = self .right = None
def averageOfLevels(root):
q = Queue()
q.put(root)
while ( not q.empty()):
Sum = 0
count = 0
temp = Queue()
while ( not q.empty()):
n = q.queue[ 0 ]
q.get()
Sum + = n.val
count + = 1
if (n.left ! = None ):
temp.put(n.left)
if (n.right ! = None ):
temp.put(n.right)
q = temp
print (( Sum * 1.0 / count), end = " " )
if __name__ = = '__main__' :
root = None
root = newNode( 4 )
root.left = newNode( 2 )
root.right = newNode( 9 )
root.left.left = newNode( 3 )
root.left.right = newNode( 8 )
root.right.right = newNode( 7 )
averageOfLevels(root)
|
C#
using System;
using System.Collections.Generic;
class GfG
{
class Node
{
public int val;
public Node left, right;
}
static void averageOfLevels(Node root)
{
Queue<Node> q = new Queue<Node> ();
q.Enqueue(root);
int sum = 0, count = 0;
while ((q.Count!=0))
{
sum = 0;
count = 0;
Queue<Node> temp = new Queue<Node> ();
while (q.Count != 0)
{
Node n = q.Peek();
q.Dequeue();
sum += n.val;
count++;
if (n.left != null )
temp.Enqueue(n.left);
if (n.right != null )
temp.Enqueue(n.right);
}
q = temp;
Console.Write((sum * 1.0 / count) + " " );
}
}
static Node newNode( int data)
{
Node temp = new Node();
temp.val = data;
temp.left = null ;
temp.right = null ;
return temp;
}
public static void Main(String[] args)
{
Node root = null ;
root = newNode(4);
root.left = newNode(2);
root.right = newNode(9);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
Console.WriteLine( "Averages of levels : " );
Console.Write( "[" );
averageOfLevels(root);
Console.WriteLine( "]" );
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .left = null ;
this .right = null ;
this .val = data;
}
}
function averageOfLevels(root)
{
let q = [];
q.push(root);
let sum = 0, count = 0;
while (q.length > 0)
{
sum = 0;
count = 0;
let temp = [];
while (q.length > 0)
{
let n = q[0];
q.shift();
sum += n.val;
count++;
if (n.left != null )
temp.push(n.left);
if (n.right != null )
temp.push(n.right);
}
q = temp;
document.write((sum * 1.0 / count) + " " );
}
}
function newNode(data)
{
let temp = new Node(data);
return temp;
}
let root = null ;
root = newNode(4);
root.left = newNode(2);
root.right = newNode(9);
root.left.left = newNode(3);
root.left.right = newNode(5);
root.right.right = newNode(7);
document.write( "Averages of levels : " + "</br>" );
document.write( "[" );
averageOfLevels(root);
document.write( "]" + "</br>" );
</script>
|
Complexity Analysis:
- Time complexity : O(n).
The whole tree is traversed atmost once. Here, n refers to the number of nodes in the given binary tree. - Auxiliary Space : O(n).
The size of queues can grow upto atmost the maximum number of nodes at any level in the given binary tree. Here, n refers to the maximum number of nodes at any level in the input tree.
Another Approach using the Map
Follow the below steps to solve the problem:
- Create a map to store the {sum for each level, number of elements in each level}
- Now recursively traverse the entire tree, while tracking the height of the tree
- For every level, keep tracking the sum as well as the number of elements in that level
- Once the entire tree is traversed, the map will contain sum of all the levels and the number of elements in each level
- Traverse the map
- Divide the sum by the number of elements
- Print the answers for every level
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node *left, *right;
};
map< int , pair< double , double > > mp;
void avg(Node* r, int l)
{
if (r == NULL)
return ;
mp[l].first += r->val;
mp[l].second++;
avg(r->left, l + 1);
avg(r->right, l + 1);
}
void averageOfLevels(Node* root)
{
avg(root, 0);
for ( auto i : mp) {
cout << (i.second.first / i.second.second) << ' ' ;
}
}
Node* newNode( int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
int main()
{
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
averageOfLevels(root);
}
|
Java
import java.io.*;
import java.util.*;
class Node {
int val;
Node left;
Node right;
Node( int val)
{
this .val = val;
left = null ;
right = null ;
}
}
class GFG {
Map<Integer, Double[]> mp = new HashMap<>();
public void avg(Node r, int l)
{
if (r == null )
return ;
if (!mp.containsKey(l)) {
mp.put(l, new Double[] { ( double )r.val, 1.0 });
}
else {
Double[] temp = mp.get(l);
temp[ 0 ] += r.val;
temp[ 1 ] += 1 ;
mp.put(l, temp);
}
avg(r.left, l + 1 );
avg(r.right, l + 1 );
}
public void averageOfLevels(Node root)
{
avg(root, 0 );
for (Map.Entry<Integer, Double[]> entry :
mp.entrySet()) {
System.out.print(entry.getValue()[ 0 ]
/ entry.getValue()[ 1 ]
+ " " );
}
}
public static void main(String[] args)
{
Node root = null ;
root = new Node( 4 );
root.left = new Node( 2 );
root.right = new Node( 9 );
root.left.left = new Node( 3 );
root.left.right = new Node( 8 );
root.right.right = new Node( 7 );
GFG bt = new GFG();
bt.averageOfLevels(root);
}
}
|
Python3
class Node:
def __init__( self , data):
self .val = data
self .left = None
self .right = None
class Pair:
def __init__( self , val1, val2):
self .first = val1
self .second = val2
mp = {}
def avg(r, l):
if r is None :
return
if l in mp:
mp[l] = Pair(mp[l].first + r.val, mp[l].second)
mp[l].second + = 1
else :
mp[l] = Pair(r.val, 1 )
avg(r.left, l + 1 )
avg(r.right, l + 1 )
def average_of_levels(root):
avg(root, 0 )
for key in mp:
print (mp[key].first / mp[key].second)
def new_node(data):
temp = Node(data)
return temp
root = None
root = new_node( 4 )
root.left = new_node( 2 )
root.right = new_node( 9 )
root.left.left = new_node( 3 )
root.left.right = new_node( 8 )
root.right.right = new_node( 7 )
average_of_levels(root)
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int val;
public Node left;
public Node right;
public Node( int val)
{
this .val = val;
left = null ;
right = null ;
}
}
class BinaryTree
{
public Dictionary< int , Tuple< double ,
double >> mp = new Dictionary< int , Tuple< double , double >>();
public void avg(Node r, int l)
{
if (r == null ) return ;
mp[l] = Tuple.Create(mp.ContainsKey(l) ? mp[l].Item1 + r.val :
r.val, mp.ContainsKey(l) ? mp[l].Item2 + 1 : 1);
avg(r.left, l + 1);
avg(r.right, l + 1);
}
public void averageOfLevels(Node root)
{
avg(root, 0);
foreach ( var i in mp)
{
Console.Write((i.Value.Item1 / i.Value.Item2) + " " );
}
}
public static void Main( string [] args)
{
Node root = null ;
root = new Node(4);
root.left = new Node(2);
root.right = new Node(9);
root.left.left = new Node(3);
root.left.right = new Node(8);
root.right.right = new Node(7);
BinaryTree bt = new BinaryTree();
bt.averageOfLevels(root);
}
}
|
Javascript
class Node{
constructor(data){
this .val = data;
this .left = null ;
this .right = null ;
}
}
class pair{
constructor(val1, val2){
this .first = val1;
this .second = val2;
}
}
let mp = new Map();
function avg(r, l){
if (r == null ) return ;
if (mp.has(l)){
mp.set(l, new pair(mp.get(l).first + r.val, mp.get(l).second));
mp.get(l).second += 1;
}
else
mp.set(l, new pair(r.val, 1));
avg(r.left, l+1);
avg(r.right, l+1);
}
function averageOfLevels(root){
avg(root, 0);
mp.forEach( function (value, key)
{
console.log(value.first / value.second + " " );
})
}
function newNode(data){
let temp = new Node(data);
return temp;
}
let root = null ;
root = newNode(4);
root.left = newNode(2);
root.right = newNode(9);
root.left.left = newNode(3);
root.left.right = newNode(8);
root.right.right = newNode(7);
averageOfLevels(root);
|
Time Complexity: O(N*log(N)), for storing the level wise sum in map.
Auxiliary Space: O(H), H = Height of the tree
This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.