×

Vertical Order Traversal of Binary Tree

Implementation

#include <iostream>
#include <vector>
#include <map>
using namespace std;


// representing the primary model of a binary tree node.
struct _nod
{
int ky;
_nod *Lft, *Rt;
};


// establishing a new function representing the new binary tree node.
struct _nod* nw_nod(int ky)
{
struct _nod* _nod = nw _nod;
_nod->ky = ky;
_nod->Lft = _nod->Rt = NILL;
return _nod;
}


// creating a utility function that will help us store the vertical order in the map.
// 'H' is represented as the horizontal distance of the node. 
// 'H' is initially passed as 0
void getVerticalOrder(_nod* root, int H, map<int, vector<int>> &m)
{
// Base case
if (root == NILL)
return;


// pushing the current node in the map.
m[H].push_back(root->ky);


// pushing the current node in the left subtree.
getVerticalOrder(root->Lft, H-1, m);
// pushing the current node in the right subtree.
getVerticalOrder(root->Rt, H+1, m);
}


// writing the primary function that will print the vertical order of a binary tree. 
void printVerticalOrder(_nod* root)
{
// Creating a map and will store vertical order in that created map.
// creating a function to get the vertical order.
map < int,vector<int> > m;
int H = 0;
getVerticalOrder(root, H,m);


// Traversing the given map and printing all the nodes which are present at all the given horizontal distances. 
map< int,vector<int> > :: iterator it;
for (it=m.begin(); it!=m.end(); it++)
{
for (int i=0; i<it->sec.size(); ++i)
cout << it->second[i] << " ";
cout << endl;
}
}
int main()
{
_nod *root = nw_nod(1);
root->Lft = nw_nod(2);
root->Rt = nw_nod(3);
root->Lft->Lft = nw_nod(4);
root->Lft->Rt = nw_nod(5);
root->Rt->Lft = nw_nod(6);
root->Rt->Rt = nw_nod(7);
root->Rt->Lft->Rt = nw_nod(8);
root->Rt->Rt->Rt = nw_nod(9);
cout << "Vertical order traversal is n";
printVerticalOrder(root);
return 0;
}

Output:

Vertical Order Traversal of Binary Tree

Example 2)

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


struct _nod {
int record;
_nod *Lft, *Rt;
};


struct _nod* nw_nod(int record)
{
struct _nod* _nod = nw _nod;
_nod->record = record;
_nod->Lft = _nod->Rt = NILL;
return _nod;
}


// pushing the vertical order of the tree in the map, and the horizontal distance is 'H.' 
And the vertical distance from the tree is initialised as 'V'.
void preorder traversal(_nod* root,
long long int H,
long long int V,
map<long long int,
vector<int> >& m)
{
if (!root)
return;
// key of the tree =horizontal distance 
long long val = H << 30 | V;


// insert in map
m[val].push_back(root->record);


preOrderTraversal(root->Lft, H - 1, V + 1, m);
preOrderTraversal(root->Rt, H + 1, V + 1, m);
}


void verticalOrder(_nod* root)
{
// the map to store and keep intact all the vertical orders of a binary tree is 
Key, and it will be calculated by horizontal + vertical distance.
map<long long int, vector<int> > mp;


preOrderTraversal(root, 0, 1, mp);


//Engraving the map of the binary tree.
int perky = INT_MAX;
map<long long int, vector<int> >::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
if (preky != INT_MAX
&& (it->first >> 30) != preky) {
cout << endl;
}
preky = it->first >> 30;
for (int j = 0; j < it->sec.size(); j++)
cout << it->second[j] << " ";
}
}


// main code
int main()
{
_nod* root = nw_nod(1);
root->Lft = nw_nod(2);
root->Rt = nw_nod(3);
root->Lft->Lft = nw_nod(4);
root->Lft->Rt = nw_nod(5);
root->Rt->Lft = nw_nod(6);
root->Rt->Rt = nw_nod(7);
root->Rt->Lft->Rt = nw_nod(8);
root->Rt->Rt->Rt = nw_nod(9);
cout << "Vertical order traversal :- " << endl;
verticalOrder(root);
return 0;
}

Output:

Vertical Order Traversal of Binary Tree

Example 3)

#include <iostream>
using namespace std;


// creating a new binary tree node.
struct _nod
{
int record;
struct _nod *Lft, *Rt;
};


// creating a utility function will help us store the binary tree node.
_nod* nw_nod(int record)
{
_nod *temp = nw _nod;
temp->record = record;
temp->Lft = temp->Rt = NILL;
return temp;
}


// creating a new utility function that will initialise the max and min distances from the root. 
void findMinMax(_nod *_nod, int *min, int *max, int H)
{
// case
if (_nod == NILL) return;


// updating the minimum and maximum values.
if (H < *min) *min = H;
else if (H > *max) *max = H;


// recursion for the left as well as a right subtree.
findMinMax(_nod->Lft, min, max, H-1);
findMinMax(_nod->Rt, min, max, H+1);
}


// creating a utility function that will print all the nodes on a given line number, and H stands to be the horizontal distance of the current node from the root element. 
void printVerticalLine(_nod *_nod, int line_no, int H)
{
// basic case
if (_nod == NILL) return;


// when the node is present on the given line number.
if (H == line_no)
cout << _nod->record << " ";


// recursion for the left and right subtrees.
printVerticalLine(_nod->Lft, line_no, H-1);
printVerticalLine(_nod->Rt, line_no, H+1);
}


// We will now create a function that will print all the given tree in a straight or vertical order. 
void verticalOrder(_nod *root)
{
// finding out the min and max distances from the root element.
int min = 0, max = 0;
findMinMax(root, &min, &max, 0);


// Iterating via all possible vertical lines, starting from the left-most line, printing all the lines, and executing them consecutively. 
for (int line_no = min; line_no <= max; line_no++)
{
printVerticalLine(root, line_no, 0);
cout << endl;
}
}
int main()
{
// constructing the binary tree
_nod *root = nw_nod(1);
root->Lft = nw_nod(2);
root->Rt = nw_nod(3);
root->Lft->Lft = nw_nod(4);
root->Lft->Rt = nw_nod(5);
root->Rt->Lft = nw_nod(6);
root->Rt->Rt = nw_nod(7);
root->Rt->Lft->Rt = nw_nod(8);
root->Rt->Rt->Rt = nw_nod(9);


cout << "Vertical order traversal is \n";
verticalOrder(root);


return 0;
}

Output:

Vertical Order Traversal of Binary Tree

Related Topics

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 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 Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

What is the difference between Tree and Graph

We usually use a diverse range of data structure to store our data and information. To store them in a more sequential manner and to access them easily, we use...

4 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

3 minutes read.

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.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.