Output: 1 Explanation: As the height of given tree is 3 and size of given tree is 3 , the density is (3/3) = 1
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.
Approach:
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, the idea is to compute the size of the binary tree while finding the height of the binary tree. Then simply 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 tree. Auxiliary Space : O(h), where h is the height of the tree.