VOOZH about

URL: https://www.geeksforgeeks.org/dsa/density-of-binary-tree-using-level-order-traversal/

⇱ Density of Binary Tree using Level Order Traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Density of Binary Tree using Level Order Traversal

Last Updated : 11 Jul, 2025

Given a Binary Tree, the task is to find the density of it by doing one traversal of it. Density of Binary Tree = Size / Height.

Examples:

Input:

👁 density_of_binary_tree_1x

Output: 1.5
Explanation: As the height of given tree is 2 and size of given tree is 3 , the density is (3/2) = 1.5

Input:

👁 density_of_binary_tree_2_1x

Output: 1
Explanation: As the height of given tree is 3 and size of given tree is 3 , the density is (3/3) = 1

Approach:

The idea is to use level order traversal to calculate the height and size of the binary tree in one traversal. While traversing the tree, increment the height after each level of traversal and increment the size after each node. Return the value of (size/ height).

Below is the implementation of the above approach:  


Output
1.5

Time Complexity: O(n) where n is the number of nodes in the binary tree.
Auxiliary Space: O(n)

Related article:

Comment
Article Tags: