Averages of Levels in Binary Tree

01 Jul, 2021
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.
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.
C++
Java
Python3
C#
Javascript
// C++ program to find averages of all levels// in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to   left child and a pointer to right child */struct Node {    int val;    struct Node* left, *right;}; /* Function to print the average value of the   nodes on each level */void averageOfLevels(Node* root){    vector<float> res;     // Traversing level by level    queue<Node*> q;    q.push(root);     while (!q.empty()) {         // Compute sum of nodes and        // count of nodes in current        // level.        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) << " ";    }} /* Helper function that allocates a   new node with the given data and   NULL left and right pointers. */Node* newNode(int data){    Node* temp = new Node;    temp->val = data;    temp->left = temp->right = NULL;    return temp;} // Driver codeint main(){    /* Let us construct a Binary Tree        4       / \      2   9     / \   \    3   5   7 */     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 program to find averages of all levels// in a binary tree.import java.util.*;class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node {    int val;    Node left, right;} /* Function to print the average value of thenodes on each level */static void averageOfLevels(Node root){    //vector<float> res;     // Traversing level by level    Queue<Node> q = new LinkedList<Node> ();    q.add(root);    int sum = 0, count  = 0;     while (!q.isEmpty()) {         // Compute sum of nodes and        // count of nodes in current        // level.        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) + " ");    }} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */static Node newNode(int data){    Node temp = new Node();    temp.val = data;    temp.left = null;    temp.right = null;    return temp;} // Driver codepublic static void main(String[] args){    /* Let us construct a Binary Tree        4    / \    2 9    / \ \    3 5 7 */     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 program to find averages of# all levels in a binary tree. # Importing Queuefrom queue import Queue # Helper class that allocates a# new node with the given data and# None left and right pointers.class newNode:    def __init__(self, data):        self.val = data        self.left = self.right = None     # Function to print the average value# of the nodes on each leveldef averageOfLevels(root):     # Traversing level by level    q = Queue()    q.put(root)    while (not q.empty()):         # Compute Sum of nodes and        # count of nodes in current        # level.        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 = " ") # Driver codeif __name__ == '__main__':     # Let us construct a Binary Tree    #     4    # / \    # 2 9    # / \ \    # 3 5 7    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) # This code is contributed by PranchalK
// C# program to find averages of all levels// in a binary tree.using System;using System.Collections.Generic; class GfG{     /* A binary tree node has data, pointer to    left child and a pointer to right child */    class Node    {        public int val;        public Node left, right;    }     /* Function to print the average value of the    nodes on each level */    static void averageOfLevels(Node root)    {        //vector<float> res;         // Traversing level by level        Queue<Node> q = new Queue<Node> ();        q.Enqueue(root);        int sum = 0, count = 0;         while ((q.Count!=0))        {             // Compute sum of nodes and            // count of nodes in current            // level.            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) + " ");        }    }     /* Helper function that allocates a    new node with the given data and    NULL left and right pointers. */    static Node newNode(int data)    {        Node temp = new Node();        temp.val = data;        temp.left = null;        temp.right = null;        return temp;    }     // Driver code    public static void Main(String[] args)    {        /* Let us construct a Binary Tree            4        / \        2 9        / \ \        3 5 7 */         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("]");    }} // This code has been contributed by// 29AjayKumar
<script> // Javascript program to find averages of// all levels in a binary tree.class Node{    constructor(data)    {        this.left = null;        this.right = null;        this.val = data;    }} // Function to print the average value// of the nodes on each levelfunction averageOfLevels(root){         // Traversing level by level    let q = [];    q.push(root);    let sum = 0, count  = 0;     while (q.length > 0)    {                 // Compute sum of nodes and        // count of nodes in current        // level.        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) + " ");    }} // Helper function that allocates a// new node with the given data and// NULL left and right pointers.function newNode(data){    let temp = new Node(data);    return temp;} // Driver code /* Let us construct a Binary Tree     4    / \   2   9  / \   \ 3   5   7 */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>"); // This code is contributed by divyeshrabadiya07 </script>
Output: 
Average of levels: 
[4 5.5 5]
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. 
Averages of Levels in Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAverages of Levels in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=BgRuUsatWhw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prerna saini
PranchalKatiyar
29AjayKumar
nidhi_biet
divyeshrabadiya07
tree-level-order
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Sliding Window Maximum (Maximum of all subarrays of size k)
What is Priority Queue | Introduction to Priority Queue
LRU Cache Implementation
Queue | Set 1 (Introduction and Array Implementation)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Introduction to Tree Data Structure