# Density of Binary Tree in One Traversal in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find the density of the binary tree in a single traversal.

The density of the binary tree is obtained by dividing the size of the tree by the height of the tree.

The size of the binary tree is the total number of nodes present in the given binary tree.

The height of the binary tree is the max depth of the leaf node from the root node.

Let's see the steps to solve the problem.

• Initialize the binary tree dummy data.

• Find the size and height of the tree.

• Recursively count the height of the tree.

• Return the left node tree height if it greater than the right node tree height else return the right node tree height by adding to both 1.

• Increment the size of the node.

• Calculate the density of the tree using the formula $$size\:of\:Tree\:/\:height\:of\:Tree$$.

• Print the density of the tree.

## Example

Let's see the code.

#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode(int data) {
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
int findHeightAndSizeOfTree(Node* node, int &size) {
if (node == NULL) {
return 0;
}
int leftTreeCount = findHeightAndSizeOfTree(node->left, size);
int rightTreeCount = findHeightAndSizeOfTree(node->right, size);
size++;
return (leftTreeCount > rightTreeCount) ? leftTreeCount + 1 : rightTreeCount + 1;
}
float treeDensity(Node* root) {
if (root == NULL) {
return 0;
}
int treeSize = 0;
int treeHeight = findHeightAndSizeOfTree(root, treeSize);
return (float)treeSize/treeHeight;
}
int main() {
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << treeDensity(root) << endl;
return 0;
}

## Output

If you execute the above program, then you will get the following result.

2.33333

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.