Given a Binary Tree, find density of it by doing one traversal of it.
Density of Binary Tree = Size / Height
Examples:
Input: Root of following tree
10
/ \
20 30
Output: 1.5
Height of given tree = 2
Size of given tree = 3
Input: Root of following tree
10
/
20
/
30
Output: 1
Height of given tree = 3
Size of given tree = 3
Density of a Binary Tree indicates, how balanced Binary Tree is. For example density of a skewed tree is minimum and that of a perfect tree is maximum.
We strongly recommend you to minimize your browser and try this yourself first.
Two traversal based approach is very simple. First find the height using one traversal, then find the size using another traversal. Finally return the ratio of two values.
To do it in one traversal, we compute size of Binary Tree while finding its height. Below is C++ implementation.
C++
#include<bits/stdc++.h>
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 heighAndSize(Node* node, int &size)
{
if (node==NULL)
return 0;
int l = heighAndSize(node->left, size);
int r = heighAndSize(node->right, size);
size++;
return (l > r) ? l + 1 : r + 1;
}
float density(Node* root)
{
if (root == NULL)
return 0;
int size = 0;
int _height = heighAndSize(root, size);
return ( float )size/_height;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
printf ( "Density of given binary tree is %f" ,
density(root));
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class Size
{
int size = 0 ;
}
class BinaryTree
{
Node root;
int heighAndSize(Node node, Size size)
{
if (node == null )
return 0 ;
int l = heighAndSize(node.left, size);
int r = heighAndSize(node.right, size);
size.size++;
return (l > r) ? l + 1 : r + 1 ;
}
float density(Node root)
{
Size size = new Size();
if (root == null )
return 0 ;
int _height = heighAndSize(root, size);
return ( float ) size.size / _height;
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
System.out.println( "Density of given Binary Tree is : "
+ tree.density(tree.root));
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def heighAndSize(node, size):
if (node = = None ) :
return 0
l = heighAndSize(node.left, size)
r = heighAndSize(node.right, size)
size[ 0 ] + = 1
return l + 1 if (l > r) else r + 1
def density(root):
if (root = = None ) :
return 0
size = [ 0 ]
_height = heighAndSize(root, size)
return size[ 0 ] / _height
if __name__ = = '__main__' :
root = newNode( 1 )
root.left = newNode( 2 )
root.right = newNode( 3 )
print ( "Density of given binary tree is " ,
density(root))
|
C#
using System;
class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class Size
{
public int size = 0;
}
class BinaryTree
{
Node root;
int heighAndSize(Node node,
Size size)
{
if (node == null )
return 0;
int l = heighAndSize(node.left, size);
int r = heighAndSize(node.right, size);
size.size++;
return (l > r) ? l + 1 : r + 1;
}
float density(Node root)
{
Size size = new Size();
if (root == null )
return 0;
int _height = heighAndSize(root, size);
return ( float ) size.size / _height;
}
static public void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
Console.WriteLine( "Density of given " +
"Binary Tree is : " +
tree.density(tree.root));
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
class Size
{
constructor()
{
this .size = 0;
}
}
var root = null ;
function heighAndSize(node, size)
{
if (node == null )
return 0;
var l = heighAndSize(node.left, size);
var r = heighAndSize(node.right, size);
size.size++;
return (l > r) ? l + 1 : r + 1;
}
function density(root)
{
var size = new Size();
if (root == null )
return 0;
var _height = heighAndSize(root, size);
return size.size / _height;
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
document.write( "Density of given " +
"Binary Tree is : " +
density(root));
</script>
|
Output
Density of given binary tree is 1.500000
Time Complexity: O(N), where N is the number of nodes in the tree.
Space Complexity: O(H), where H is the height of the tree
BFS Approach :
Explanation of the Breadth-First Search (BFS) approach to calculate the density of a binary tree :
- Initialize two variables,
size
and height
, to keep track of the total number of nodes visited and the height of the tree, respectively.
- Created an empty queue for BFS traversal.
- Enqueueing by adding the root node of the binary tree to the queue.
- Begin the BFS traversal loop. At each step, process nodes level by level.
- Get the number of nodes in the current level by checking the queue size. Add
levelSize
to the size
variable to count the total number of nodes in the tree. Increment the height
variable to track the height of the tree.
- Now for each node in the current level, dequeue it from the queue and enqueue its left and right child nodes (if they exist) into the queue. This ensures that the next level will be processed in the next iteration of the traversal loop.
- Once the BFS traversal is complete, calculate the density of the binary tree using the formula:
Density = Size / Height
.
- Finally return the calculated density as the result of the function.
C++
#include <bits/stdc++.h>
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;
}
float densityBFS(Node* root)
{
if (root == NULL)
return 0;
int size = 0;
int height = 0;
std::queue<Node*> q;
q.push(root);
while (!q.empty()) {
int levelSize = q.size();
size += levelSize;
height++;
for ( int i = 0; i < levelSize; i++) {
Node* current = q.front();
q.pop();
if (current->left)
q.push(current->left);
if (current->right)
q.push(current->right);
}
}
return ( float )size / height;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
printf ( "Density of given binary tree is %f" ,
densityBFS(root));
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node( int data) {
this .data = data;
left = right = null ;
}
}
public class BinaryTreeDensity {
static float densityBFS(Node root) {
if (root == null )
return 0 ;
int size = 0 ;
int height = 0 ;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
size += levelSize;
height++;
for ( int i = 0 ; i < levelSize; i++) {
Node current = queue.poll();
if (current.left != null )
queue.add(current.left);
if (current.right != null )
queue.add(current.right);
}
}
return ( float ) size / height;
}
public static void main(String[] args) {
Node root = new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 3 );
System.out.printf( "Density of given binary tree is %.2f" , densityBFS(root));
}
}
|
Python3
from queue import Queue
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def densityBFS(root):
if root is None :
return 0.0
size = 0
height = 0
q = Queue()
q.put(root)
while not q.empty():
levelSize = q.qsize()
size + = levelSize
height + = 1
for _ in range (levelSize):
current = q.get()
if current.left:
q.put(current.left)
if current.right:
q.put(current.right)
return float (size) / height
if __name__ = = "__main__" :
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
density = densityBFS(root)
print (f "Density of given binary tree is {density:.6f}" )
|
C#
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class BinaryTreeDensity {
static float DensityBFS(Node root)
{
if (root == null )
return 0;
int size = 0;
int height = 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
int levelSize = q.Count;
size += levelSize;
height++;
for ( int i = 0; i < levelSize; i++) {
Node current = q.Dequeue();
if (current.left != null )
q.Enqueue(current.left);
if (current.right != null )
q.Enqueue(current.right);
}
}
return ( float )size / height;
}
static void Main( string [] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
Console.WriteLine(
"Density of the given binary tree is "
+ DensityBFS(root));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function densityBFS(root) {
if (root === null )
return 0;
let size = 0;
let height = 0;
const queue = [];
queue.push(root);
while (queue.length > 0) {
const levelSize = queue.length;
size += levelSize;
height++;
for (let i = 0; i < levelSize; i++) {
const current = queue.shift();
if (current.left !== null )
queue.push(current.left);
if (current.right !== null )
queue.push(current.right);
}
}
return size / height;
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
console.log(`Density of given binary tree is ${densityBFS(root).toFixed(2)}`);
|
Output
Density of given binary tree is 1.500000
Time Complexity: O(N), where N is the number of nodes in the tree.
Space Complexity: O(H), where H is the height of the tree
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
15 Nov, 2023
Like Article
Save Article