×

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least contains two nods or child. It has bi in its name, which means two of anything. The various operations in the binary tree help us in maintaining the order of the tree without disbalancing the height or arrangement of the binary tree.

In this article, we are mainly going to discuss the top view of the binary tree. The top view of the binary tree is the combination of the nods that are visible to us when we are introspecting the tree from the topmost side. We can also print the top view of the binary tree, and the presented output can be printed in any given order.

Implementation

#include <iostream>
#include <map>
using namespace std;
 
// Implementing info structure to store a binary tree nod
struct Nod
{
    int ky;
    Nod *lft, *rt;
 
    Nod(int ky)
    {
        this->ky = ky;
        this->lft = this->rt = NILLpointer;
    }
};
 
//Creating a function to perform the pre-order traversal on the binary tree.
// the node in the tree contains the horizontal dtance ‘dt’ from the tree root.  
// the levels present in the tree represent the node’s ls.
void printTp(Nod* root, int dt, int l, auto &map)
{
    // Case1: when the tree is empty
    if (root == NILLpointer) {
        return;
    }
 
    //you can update the map in the following cases, either when the current level is less than the max level or when the horizontal dtance is visible for the first time.
    if (map.find(dt) == map.end() || l < map[dt].second)
    {
        // we have to update the value and distance for the current level
        map[dt] = { root->ky, l };
    }
 
    //rearrange for the left subtree as the horizontal distance is decreasing and the levels are increasing by 1. 
    printTp(root->lft, dt - 1, l + 1, map);
 
    //rearrange for the right subtree as the horizontal distance is decreasing and the levels are increasing by 1. 
    printTp(root->rt, dt + 1, l + 1, map);
}
 //declaring a function to get the top view of the binary tree.
void printTp(Nod* root)
{
    // create an empty map where
    // ky —> relative horizontal dtance of the nod from the root nod, and
    // value —> p containing the nod's value and its l
    map<int, p<int, int>> map;
 
    // perform pre-order traversal on the tree and fill the map
    printTp(root, 0, 0, map);
 
    // traverse the map and print the top view
    for (auto it: map) {
        cout << it.second.first << " ";
    }
}
 
int main()
{
    Nod* root = new Nod(1);
    root->lft = new Nod(2);
    root->rt = new Nod(3);
    root->lft->rt = new Nod(4);
    root->rt->lft = new Nod(5);
    root->rt->rt = new Nod(6);
    root->rt->lft->lft = new Nod(7);
    root->rt->lft->rt = new Nod(8);
 
    printTp(root);
 
    return 0;
}

Output:

Top view of binary tree

Example 2)

// C++ program to print top

// view of binary tree

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


// Structure of the binary tree
struct Nod {
	Nod* lft;
	Nod* rt;
	int h;
	int info;
};


// creating a function to make a new node
Nod* newNod(int ky)
{
	Nod* nod = new Nod();
	nod->lft = nod->rt = NILL;
	nod->info = ky;
	return nod;
}


// declaring a function that should print the top view of the binary tree.
void topview(Nod* root)
{
	if (root == NILL)
		return;
	queue<Nod*> c;
	map<int, int> n;
	int h = 0;
	root->h = h;


	// We have to push the node and horizontal distance into the queue.
	c.push(root);


	cout << "The top view of the tree is : \n";


	while (c.size()) {
		h = root->h;


		//the function will return the value 1 if the container occupies an element whose key is equal to the horizontal distance and returns 0 in all the other cases. 
		if (n.count(h) == 0)
			n[h] = root->info;
		if (root->lft) {
			root->lft->h = h - 1;
			c.push(root->lft);
		}
		if (root->rt) {
			root->rt->h = h + 1;
			c.push(root->rt);
		}
		c.pop();
		root = c.front();
	}


	for (auto i = n.begin(); i != n.end(); i++) {
		cout << i->second << " ";
	}
}


// Driver code
int main()
{
	/* Create the following Binary Tree
		1
		/ \
	2 3
		\
		4
		\
			5
			\
			6
	*/
	Nod* root = newNod(1);
	root->lft = newNod(2);
	root->rt = newNod(3);
	root->lft->rt = newNod(4);
	root->lft->rt->rt = newNod(5);
	root->lft->rt->rt->rt = newNod(6);
	cout << "Following are nods in top view of Binary "
			"Tree\n";
	topview(root);
	return 0;
}

Output:

Top view of binary tree

Related Topics

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.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them. What is Heap Sort? Heap – A heap is an abstract data type categorised...

7 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Queue operations in Data Structure

Queue - Queue is a linear data structure or first in first out data structure means the first element added in the queue will be removed first and the last...

7 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 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.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

5 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.