Averages of Levels in Binary Tree


Given a non-empty binary tree, print the average value of the nodes on each level.


Input : 
   / \
  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)

  1. Start by pushing the root node into the queue. Then, remove a node from the front of the queue.
  2. For every node removed from the queue, push all its children into a new temporary queue.
  3. Keep on popping nodes from the queue and adding these node’ s children to the temporary queue till queue becomes empty.
  4. Every time queue becomes empty, it indicates that one level of the tree has been considered.
  5. 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.
  6. After each level has been considered, again initialize the queue with temporary queue and continue the process till both queues become empty.
// 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;

    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();
            sum += n->val;
            if (n->left != NULL)
            if (n->right != NULL)
        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 code
int main()
    /* Let us construct a Binary Tree
       / \
      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);
    return 0;


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.

This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

2 Average Difficulty : 2/5.0
Based on 3 vote(s)