Given a Binary Tree, The task is 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. The horizontal distance of the left child of a node x is equal to a horizontal distance of x minus 1, and that of a right child is the horizontal distance of x plus 1.
The following are steps to print the Bottom View of the Binary Tree.
- Initialize variable hd = 0,map m with int-int key value pair and queue q to store nodes level-wise.
- Set root->hd = hd and push root in q
- Run a while loop till q is empty
- Store the front element in node temp and temp ->hd in variable hd and pop it then set temp->data as value for key hd in m i.e. m[hd] = temp->data.
- If temp -> left is not NULL and set temp->left->hd = hd-1 as well as If temp -> right is not NULL and set temp->right->hd = hd+1 respectively.
- Iterate over the keys and print the values.
Related Article : https://www.geeksforgeeks.org/bottom-view-binary-tree/