DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree

The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be exactly one node that will appear in the bottom view. The horizontal distance is measured with the root serving as a reference; then, we measure each node’s left and right deviations.

Here, the nodes four, eight, six, nine, and seven are viewed from the bottom hence they will come in the bottom view of a tree.

Approach

  1. Do a level order traversal of the tree.
  2. Assign horizontal distance to each node of Binary Tree and replace the same horizontal distance node in a map with key as the distance to obtain the Bottom View.
  3. Make key as distance and data as value for the map.
  4. Perform it for every node in the tree.

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 #define mkp make_pair // macro
 struct Node  // Tree structure
 {
     int data;
     int distance;
     Node *left, *right;
     Node(int val)
     {
         data = val;
         left = NULL;
         right = NULL;
     }
 };
 // Function to print Bottom View of Binary Tree
 void BottomView(Node *root)
 {
     if (root == NULL)
         return;
     // initialising variables
     queue<Node *> q;
     q.push(root);
     root -> distance = 0;
     map<int, int> mp;
     // variable to store distance of nodes
     int distance;
     // assigning horizontal distance to each node of Binary Tree
     // and replacing nodes of the same horizontal distance in a map with
     // key as the distance to obtain the Bottom View
     while (!q.empty())
     {
         // extract the node at the front of queue
         Node *temp = q.front();
         distance = temp -> distance;
         // make key as distance and data as value for map
         mp[distance] = temp -> data;
         // remove the extract node from queue
         q.pop();
         // when left child exists, assign horizontal distance to it,
         // and push it to the queue
         if (temp -> left != NULL)
         {
             temp -> left -> distance = distance - 1;
             q.push(temp -> left);
         }
         // when right child exists, assign horizontal distance to it,
         // and push it to the queue
         if (temp -> right != NULL)
         {
             temp -> right -> distance = distance + 1;
             q.push(temp -> right);
         }
     }
     /*
         Map mp contains:
         [-2] -> 4
         [-1] -> 8
         [0] -> 6
         [1] -> 9
         [2] -> 7
     */
     cout << "Bottom View of Binary Tree: " << endl;
     map<int, int> :: iterator it;
     // Iterate over the map keys i.e -2, -1, 0, 1, 2
     for (it = mp.begin(); it != mp.end(); it++)
         cout << it -> second << " ";
 }
 // Driver Function
 int main()
 {
     map<int, Node *> m;
     // Input number of edges
     int n;
     cin >> n;
     Node *root = NULL;
     /*
         Input Format:
             Input:
                     3
                     1 2 L
                     1 3 R
                     2 4 L
                     This means there are 3 edges
                     2 is the left child of 1,
                     3 is the right child of 1,
                     4 is the left child of 2.
     */
     for (int i = 0; i < n; i++)
     {
         int node1, node2;
         char direction;
         cin >> node1 >> node2 >> direction;
         Node *parent, *child;
         if (m.find(node1) == m.end())
         {
             parent = new Node(node1);
             m[node1] = parent;
             if (root == NULL)
                 root = parent;
         }
         else
             parent = m[node1];
         child = new Node(node2);
         if (direction == 'L')
             parent -> left = child;
         else
             parent -> right = child;
         m[node2] = child;
     }
     // call to BottomView function
     BottomView(root);
     return 0;
 } 

    Input:

    8

    1 2 L

    1 3 R

    2 4 L

    2 5 R

    3 6 L

    3 7 R

    5 8 L

    6 9 R

Visualization of the tree

            1

         /     \

        2       3

      /   \    /   \

    4     5 6     7

          /    \

        /       \

       8        9

Output:

Bottom View of Binary Tree:

4 8 6 9 7


Related Topics

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.