Tree bottom view

i am not able to build logic to print bottom view of binary tree

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.

Examples:

                  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.

Approach

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.

you can take help from reference Code

Reference Code

if you have more doubts regarding this feel free to ask
i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved :grinning:

we have not studied tree map yet ??

i don’t understand what are you saying

if you have not studied tree then
why are you asking question on Tree Bottom View??

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.