![]() |
VOOZH | about |
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_1xOutput: 1.5
Explanation: As the height of given tree is 2 and size of given tree is 3 , the density is (3/2) = 1.5Input:
👁 density_of_binary_tree_2_1xOutput: 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:
1.5
Time Complexity: O(n) where n is the number of nodes in the binary tree.
Auxiliary Space: O(n)
Related article: