×

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation of the same and understand its works.

Implementation

// C++ Program to print Bottom View of Binary Tree

#include<bits/stdc++.h>
using namespace std;


// Creating a class
struct Nod
{
	int record; 
	int h; //horizontal distance from the node
	Nod *lft, *rt; 


	// Constructor of a tree node
	Nod(int ky)
	{
		record = ky;
		h = INT_MAX;
		lft = rt = NILL;
	}
};
//creating a way that prints the bottom look of the tree.
Void bottomView(Nod *root)
{
	if (root == NILL)
		return;


	// Initialize a variable 'h' with 0
	int h = 0;


	// Creating a tree map that will store the value.
	// sorted on key data
	map<int, int> n;


	// Creating a queue that will store the value of the node's levels.
	queue<Nod *> c;


//creating a horizontal distance and initializing it with the value present in the root node and adding it to the queue.	
	root->h = h;
	c.push(root); // In STL, push() is used enqueue an item


//Creating a loop.
	while (!c.empty())
	{
		Nod *temp = c.front();
		c.pop(); 


		//From the dequeued node, we must take out the horizontal distance for evaluation.
		h = temp->h;


		//whenever we find a similar horizontal distance, we have to replace it on the map immediately.
		n[h] = temp->record;


		//If the node has a left child, we must add it to the queue, and the horizontal distance will become h-1.
		if (temp->lft != NILL)
		{
			temp->lft->h = h-1;
			c.push(temp->lft);
		}


	//If the node has the right child, we must add it to the queue, and the horizontal distance will become h+1.		
		if (temp->rt != NILL)
		{
			temp->rt->h = h+1;
			c.push(temp->rt);
		}
	}


	//Visiting each of the map items using for loop.
	for (auto i = n.begin(); i != n.end(); ++i)
		cout << i->second << " ";
}


// Driver Code
int main()
{
	Nod *root = new Nod(20);
	root->lft = new Nod(8);
	root->rt = new Nod(22);
	root->lft->lft = new Nod(5);
	root->lft->rt = new Nod(3);
	root->rt->lft = new Nod(4);
	root->rt->rt = new Nod(25);
	root->lft->rt->lft = new Nod(10);
	root->lft->rt->rt = new Nod(14);
	cout << "Bottom view of the given binary tree :\n";
	bottomView(root);
	return 0;
}

Output:

Bottom view of the binary tree

Using a different approach towards the same.

Example 2)

// C++ Program to print Bottom View of Binary Tree

#include <bits/stdc++.h>
#include <map>
using namespace std;


struct Nod
{
	int record;
	// horizontal distance from the node
	int h;
	Nod * lft, * rt;
	// Constructor from the tree nod
	Nod(int ky)
	{
		record = ky;
		h = INT_MAX;
		lft = rt = NILL;
	}
};


void printBottomViewUtil(Nod * root, int currentent, int h, map <int, pr <int, int>> & n)
{
	if (root == NILL)
		return;
	//By any chance, if the node of the horizontal distance is not present, add it to the map.
	if (n.find(h) == n.end())
	{
		n[h] = make_pr(root -> record, current);
	}
	//Check the height of the nodes from the horizontal distance.	
	else
	{
		pr < int, int > g = n[h];
		if (g.second <= current)
		{
			n[h].second = current;
			n[h].first = root -> record;
		}
	}
	
	printBottomViewUtil(root -> lft, current + 1, h - 1, n);
		printBottomViewUtil(root -> rt, current + 1, h + 1, n);
}


void printBottomView(Nod * root)
{
	//Creating a map that stores horizontal distance from height and records.
	map < int, pr < int, int > > n;
	
	printBottomViewUtil(root, 0, 0, n);
	
	// Prints the values stored by printBottomViewUtil()
	map < int, pr < int, int > > ::iterator it;
	for (it = n.begin(); it != n.end(); ++it)
	{
		pr < int, int > g = it -> second;
		cout << g.first << " ";
	}
}


int main()
{
	Nod * root = new Nod(20);
	root -> lft = new Nod(8);
	root -> rt = new Nod(22);
	root -> lft -> lft = new Nod(5);
	root -> lft -> rt = new Nod(3);
	root -> rt -> lft = new Nod(4);
	root -> rt -> rt = new Nod(25);
	root -> lft -> rt -> lft = new Nod(10);
	root -> lft -> rt -> rt = new Nod(14);
	cout << "Bottom view of the given binary tree :\n";
	printBottomView(root);
	return 0;
}

Output:

Bottom view of the binary tree

Related Topics

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

4 minutes read.

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

4 minutes read.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

3 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.