• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
August 16, 2024 |570 Views

Bottom View of a Binary Tree

Description
Discussion

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. 

  1. Initialize variable hd = 0,map m with int-int key value pair and queue q to store nodes level-wise.
  2. Set root->hd = hd and push root in q
  3. Run a while loop till q is empty
    1. 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. 
    2. 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.
  4. Iterate over the keys and print the values.

 

Related Article : https://www.geeksforgeeks.org/bottom-view-binary-tree/