×

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

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

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

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

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.

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

Introduction to 2D-Arrays

Two Dimensional Array Technical Definitions An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table...

3 minutes read.

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

6 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

AVL tree in data structure c++

AVL tree is generally known as the self-sustained and most balanced tree in the field of a binary search tree. It was also widely known as the height-balanced binary tree....

6 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Extended Binary Tree

An extended binary tree is a binary tree in which all the NILL subtrees present mainly in the original trees are exchanged with the special nodes that are primarily known...

3 minutes read.