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
- Level order traversal of Binary Tree using Morris Traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Zig-Zag traversal of a Binary Tree using Recursion
- Boundary Traversal of binary tree
- Diagonal Traversal of Binary Tree
- Clockwise Triangular traversal of a Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Reverse zigzag Traversal of a Binary Tree
- Double Order Traversal of a Binary Tree
- Sideways traversal of a Complete Binary Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Clockwise Spiral Traversal of Binary Tree | Set - 2
- Clockwise Spiral Traversal of Binary Tree
- Iterative diagonal traversal of binary tree
- Triple Order Traversal of a Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Middle To Up-Down Order traversal of a Binary Tree