Given a Binary Tree, find the density of it by doing one traversal of it.
The density of binary tree is defined as:
Density of Binary Tree = Size / Height
Input : Root of following tree 10 / \ 20 30 Output : 1.5 Height of given tree = 2 Size of given tree = 3 Input : Root of the following tree 10 / 20 / 30 Output : 1 Height of given tree = 3 Size of given tree = 3
The size and height of the tree can be found in single traversal using level order traversal.
To calculate the height of the binary tree the idea is to use a “NULL” pointer as a separator between two levels. Whenever “NULL” occurs during the traversal, height is incremented.
To calculate the size of the binary tree, increment the counter for every new node encountered during the level order traversal.
Finally, use the above formula to calculate the density of the Binary Tree.
Below is the implementation of the above approach:
Time Complexity : O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Level order traversal of Binary Tree using Morris Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Flatten Binary Tree in order of Level Order Traversal
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Insertion in n-ary tree in given order and Level order traversal
- Density of Binary Tree in One Traversal
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Connect Nodes at same Level (Level Order Traversal)
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Build Binary Tree from BST such that it's level order traversal prints sorted data
- Check if the level order traversal of a Binary Tree results in a palindrome
- Specific Level Order Traversal of Binary Tree
- Boundary Level order traversal of a Binary Tree
- Level Order Binary Tree Traversal
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Zig Zag Level order traversal of a tree using single array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.