Given a Binary Tree, we need to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
20 / \ 8 22 / \ \ 5 3 25 / \ 10 14
For the above tree the output should be 5, 10, 3, 14, 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottom-most nodes at horizontal distance 0, we need to print 4.
20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14
For the above tree the output should be 5, 10, 4, 14, 25.
Method 1 – Using Queue
The following are steps to print Bottom View of Binary Tree.
1. We put tree nodes in a queue for the level order traversal.
2. Start with the horizontal distance(hd) 0 of the root node, keep on adding left child to queue along with the horizontal distance as hd-1 and right child as hd+1.
3. Also, use a TreeMap which stores key value pair sorted on key.
4. Every time, we encounter a new horizontal distance or an existing horizontal distance put the node data for the horizontal distance as key. For the first time it will add to the map, next time it will replace the value. This will make sure that the bottom most element for that horizontal distance is present in the map and if you see the tree from beneath that you will see that element.
A Java based implementation is below :
Bottom view of the given binary tree: 5 10 4 14 25
Method 2- Using HashMap()
This method is contributed by Ekta Goel.
Create a map like, map
Below is the implementation of the above:
- Sum of nodes in bottom view of Binary Tree
- Right view of Binary Tree using Queue
- Sum of nodes in top view of binary tree
- Print Right View of a Binary Tree
- Print Left View of a Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Print Nodes in Top View of Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Check if a binary tree is subtree of another binary tree | Set 2