Given a Binary Tree, find density of it by doing one traversal of it.
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 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.
Density of given binary tree is 1.5
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Density of Binary Tree using Level Order Traversal
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Level order traversal of Binary Tree using Morris Traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Level order traversal in spiral form | Using one stack and one queue
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Cartesian tree from inorder traversal | Segment Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Construct Special Binary Tree from given Inorder traversal
- Boundary Traversal of binary tree
- Perfect Binary Tree Specific Level Order Traversal
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Check if the given array can represent Level Order Traversal of Binary Search Tree
- Iterative diagonal traversal of binary tree
- Postorder traversal of Binary Tree without recursion and without stack
- Modify a binary tree to get preorder traversal using right pointers only