Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees

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