 ### C++ program to find the averages of levels of binary tree.

/*input of this binary tree program is:
4
/   \
2     9
/ \       \
3    5      7
We need to find the average of each levels.  */

#include <bits/stdc++.h>
using namespace std;
struct Node
//here a binary tree has nodes with data, we are pointing left child and right child//
{
int value;
struct Node *left, *right;
};
// Here, by this function we can find the averages of each level in atree//
void average_levels(Node *root)
{
queue<Node*>q;      /* here we are creating a queue named as 'q'. In q are going to establish the root node*/
q.push(root);
while(!q.empty())   // creating a loop when the queue is not empty. W can say this loop as 1st loop .
{
int sum=0, cnt=0;       /* initialising two variable sum and cnt which wiil find the avarages*/
queue<Node*>temp;       /*here we are creating a temporary queue 'temp' for storing the node's data in a temporery manner.
this will help to store the values of a node temourarily while q in function. */
while(!q.empty())    // Here we are creating a 2nd loop.
{
Node *n=q.front();  /*here the value front end of q will be decleared as 'n' */
q.pop();            /* then  we pop the value from q and the value will be stored in variable 'sum' */
sum+=n->value;
cnt++;              // 'cnt' increases as the values are stored in the 'sum'
if(n->left!=NULL)
temp.push(n->left);
if(n->right!=NULL)
temp.push(n->right);
}
q=temp;
cout<<(sum * 1.0 / cnt)<<endl;           // the stored value of the temporary queue will be pushed to q when q will empty.
// this is for printing the average values of each levels
}
}
/* using this function we can allocate the new node with initized data and
null left and right pointer*/
Node *newNode(int data)
Node *temp = new Node;
temp->value = data;
temp->left = temp->right = NULL;
return temp;
int main()
{
Node* root = NULL;       /*here we are putting the values in each and every nodes of a binary tree. This tree has 3 levels.*/
root = newNode(5);
root->left = newNode(4);
root->right = newNode(10);
root->left->left = newNode(2);
root->left->right = newNode(7);
root->right->right = newNode(9);
average_levels(root);
return 0;
}

/* out put of this program is:

5
7
6
*/ #### More Articles of Arkaprava Mukhopadhyay:

Name Views Likes
C++ program to find the averages of levels of binary tree. 210 0