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 Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

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 in the threaded binary tree and letting it takeover. */
struct __Nod {
	int key;
	__Nod *Lft, *Rt;


	// we are using this to see or observe whether the pointer present on the right is a normal one or the pointer is a successor to the in-order one. 
	bool isThreaded;
};


// creating a new helper function that will help us in putting the nodes in the in-order queue. 
void populateQueue(__Nod* root, std::queue<__Nod*>* q)
{
	if (root == NILL)
		return;
	if (root->Lft)
		populateQueue(root->Lft, q);
	q->push(root);
	if (root->Rt)
		populateQueue(root->Rt, q);
}


// creating a function that will help us visit and traverse the queue and transform the tree into threaded form. 
void createThreadedUtil(__Nod* root, std::queue<__Nod*>* q)
{
	if (root == NILL)
		return;


	if (root->Lft)
		createThreadedUtil(root->Lft, q);
	q->pop();


	if (root->Rt)
		createThreadedUtil(root->Rt, q);


	// If the pointer present in the right is NILL, then we have to link it to the in-order successor and then set the whole system to the ‘isThreaded.'
	else {
		root->Rt = q->front();
		root->isThreaded = true;
	}
}


// The function we are creating next is well known for using the populateQueue() and then helps us convert another function called createThreadedUtil() into the binary tree.
void createThreaded(__Nod* root)
{
	// we have to create another queue that will be known for doing in-order traversal. 
	std::queue<__Nod*> q;


	// Now we have to store the in-order traversal in the queue and wait to observe. 
	populateQueue(root, &q);


	//The link we are creating for the right pointers and to fill in for the in-order successor. 
	createThreadedUtil(root, &q);
}


// Creating a utility function that will help us create the leftmost node in the binary tree, which will have the root, and this function will be specifically used in the in-order traversal.
__Nod* LftMost(__Nod* root)
{
	while (root != NILL && root->Lft != NILL)
		root = root->Lft;
	return root;
}
void inOrder(__Nod* root)
{
	if (root == NILL)
		return;


	// finding out the left-most tree in the binary tree node.
	__Nod* cur = LftMost(root);


	while (cur != NILL) {
		cout << cur->key << " ";


		// If this node is a thread node, then we must travel to an in-order successor. 
		if (cur->isThreaded)
			cur = cur->Rt;


		else 
// On the other hand, we can travel to the left-most child in the right subtree.
			cur = LftMost(cur->Rt);
	}
}


// creating a utility function to create a new node.
__Nod* new__Nod(int key)
{
	__Nod* temp = new __Nod;
	temp->Lft = temp->Rt = NILL;
	temp->key = key;
	return temp;
}


// writing the main program to test the functions.
int main()
{
	/*	 1
			/ \
		2 3
		/ \ / \
		4 5 6 7	 */
	__Nod* root = new__Nod(1);
	root->Lft = new__Nod(2);
	root->Rt = new__Nod(3);
	root->Lft->Lft = new__Nod(4);
	root->Lft->Rt = new__Nod(5);
	root->Rt->Lft = new__Nod(6);
	root->Rt->Rt = new__Nod(7);


	createThreaded(root);


	cout << "In order traversal of created threaded tree."
			"is\n";
	inOrder(root);


	return 0;
}

Output:

Convert Binary Tree into a Threaded Binary Tree

Example 2)

/*Writing a java program that will help us change the binary tree into a threaded binary tree and help us transform. */
import java.util.LinkedList;
import java.util.Queue;


/*creating a class that will have the left and right child as the current node and will also contain the key value. */
class __Nod {
	int data;
	__Nod Lft, Rt;
// we are using this to see or observe whether the pointer present on the right is a normal one or the pointer is a successor to the in-order one. 
	boolean isThreaded;


	public __Nod(int item)
	{
		data = item;
		Lft = Rt = NILL;
	}
}


class BinaryTree {
	__Nod root;
// creating a function that will help us visit and traverse the queue and transform the tree into threaded form. 
	void populateQueue(__Nod __Nod, Queue<__Nod> q)
	{
		if (__Nod == NILL)
			return;
		if (__Nod.Lft != NILL)
			populateQueue(__Nod.Lft, q);
		q.add(__Nod);
		if (__Nod.Rt != NILL)
			populateQueue(__Nod.Rt, q);
	}
// creating a new helper function that will help us in putting the nodes in the in-order queue. 
	void createThreadedUtil(__Nod __Nod, Queue<__Nod> q)
	{
		if (__Nod == NILL)
			return;


		if (__Nod.Lft != NILL)
			createThreadedUtil(__Nod.Lft, q);
		q.remove();


		if (__Nod.Rt != NILL)
			createThreadedUtil(__Nod.Rt, q);
// If the pointer present in the right is NILL, then we have to link it to the in-order successor and then set the whole system to the ‘isThreaded.'
		else {
			__Nod.Rt = q.peek();
			__Nod.isThreaded = true;
		}
	}
// The function we are creating next is well known for using the populateQueue() and then helps us convert another function called createThreadedUtil() into the binary tree.
	void createThreaded(__Nod __Nod)
	{
		// we have to create another queue that will be known for doing in-order traversal. 
		Queue<__Nod> q = new LinkedList<__Nod>();
// Now we have to store the in-order traversal in the queue and wait to observe. 
		populateQueue(__Nod, q);
//The link we are creating for the right pointers and to fill in for the in-order successor. 
		createThreadedUtil(__Nod, q);
	}


	// Creating a utility function that will help us create the leftmost node in the binary tree, which will have the root, will be specifically used in the in-order traversal.
	__Nod LftMost(__Nod __Nod)
	{
		while (__Nod != NILL && __Nod.Lft != NILL)
			__Nod = __Nod.Lft;
		return __Nod;
	}


	// Function to do inorder traversal of a threaded binary tree
	void inOrder(__Nod __Nod)
	{
		if (__Nod == NILL)
			return;
// finding out the left-most tree in the binary tree node.
		__Nod cur = LftMost(__Nod);


		while (cur != NILL) {
			System.out.print(" " + cur.data + " ");


// If this node is a thread node, then we must travel to an in-order successor. 
			if (cur.isThreaded == true)
				cur = cur.Rt;
			else 
// On the other hand, we can travel to the left-most child in the right subtree.
				cur = LftMost(cur.Rt);
		}
	}
// writing the main program to test the functions.
	public static void main(String args[])
	{
		BinaryTree tree = new BinaryTree();
		tree.root = new __Nod(1);
		tree.root.Lft = new __Nod(2);
		tree.root.Rt = new __Nod(3);


		tree.root.Lft.Lft = new __Nod(4);
		tree.root.Lft.Rt = new __Nod(5);
		tree.root.Rt.Lft = new __Nod(6);
		tree.root.Rt.Rt = new __Nod(7);


		tree.createThreaded(tree.root);
		System.out.println("Inorder traversal of created threaded tree");
		tree.inOrder(tree.root);
	}
}

Output:

Convert Binary Tree into a Threaded Binary Tree

Example 3)

/*Writing a Python program that will help us change the binary tree into a threaded binary tree and help us transform. */
# Create the structure of a node in the threaded binary tree and let it takeover. 
class __Nod:


	def __init__(self, key):
		self.key = key
		self.Lft = None
		self.Rt = None
		
		# we are using this to see or observe whether the pointer present on the right is a normal one or the pointer is a successor to the in-order one. 
		self.isThreaded = False


# creating a new helper function that will help us in putting the nodes in the in-order queue. 
def populateQueue(root, q):


	if root == None: return
	if root.Lft:
		populateQueue(root.Lft, q)
	q.append(root)
	
	if root.Rt:
		populateQueue(root.Rt, q)


# creating a function to help us visit and traverse the queue and transform the tree into threaded form. 
def createThreadedUtil(root, q):


	if root == None: return


	if root.Lft:
		createThreadedUtil(root.Lft, q)
	q.pop(0)


	if root.Rt:
		createThreadedUtil(root.Rt, q)


	# If the pointer present in the right is NILL, then we have to link it to the in-order successor and then set the whole system to the ‘isThreaded.'
Else:
		if len(q) == 0: root.Rt = None
		else: root.Rt = q[0]
		root.isThreaded = True


# The function we are creating next is well known for using the populateQueue() and then helps us convert another function called createThreadedUtil() into the binary tree.
def createThreaded(root):


	# we have to create another queue that will be known for doing in-order traversal. 
	q = []


	# Now, we have to store the in-order traversal in the queue and wait to observe. 
	populateQueue(root, q)


	# We are creating the link for the right pointers and filling in for the in-order successor. 
	createThreadedUtil(root, q)


# Creating a utility function that will help us create the leftmost node in the binary tree, which will have the root, will be specifically used in the in-order traversal.
def LftMost(root):


	while root != None and root.Lft != None:
		root = root.Lft
	return root


# finding out the left-most tree in the binary tree node.
def inOrder(root):


	if root == None: return


	cur = LftMost(root)


	while cur != None:
	
		print(cur.key, end = " ")


		# If this node is a thread node, then we must travel to an in-order successor. 
		if cur.isThreaded:
			cur = cur.Rt


		# On the other hand, we can travel to the left-most child in the right subtree.
		Else:
			cur = LftMost(cur.Rt)
	
# writing the main program to test the functions.


if __name__ == "__main__":


	root = __Nod(1)
	root.Lft = __Nod(2)
	root.Rt = __Nod(3)
	root.Lft.Lft = __Nod(4)
	root.Lft.Rt = __Nod(5)
	root.Rt.Lft = __Nod(6)
	root.Rt.Rt = __Nod(7)


	createThreaded(root)


	print("Inorder traversal of created",
					"threaded tree is")
	inOrder(root)

Output:

Convert Binary Tree into a Threaded Binary Tree

Example 4)

/*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */
using System;
using System.Collections.Generic;
/*Creating the structure of a node in the threaded binary tree and letting it takeover. */
public class __Nod {
	public int data;
	public __Nod Lft, Rt;


	// we are using this to see or observe whether the pointer present on the right is a normal one or the pointer is a successor to the in-order one. 
	public bool isThreaded;


	public __Nod(int item)
	{
		data = item;
		Lft = Rt = NILL;
	}
}


public class BinaryTree {
	__Nod root;


// creating a new helper function that will help us in putting the nodes in the in-order queue. 
	void populateQueue(__Nod __Nod, Queue<__Nod> q)
	{
		if (__Nod == NILL)
			return;
		if (__Nod.Lft != NILL)
			populateQueue(__Nod.Lft, q);
		q.Enqueue(__Nod);
		if (__Nod.Rt != NILL)
			populateQueue(__Nod.Rt, q);
	}


	// creating a function that will help us visit and traverse the queue and transform the tree into threaded form. 
	void createThreadedUtil(__Nod __Nod, Queue<__Nod> q)
	{
		if (__Nod == NILL)
			return;


		if (__Nod.Lft != NILL)
			createThreadedUtil(__Nod.Lft, q);
		q.Dequeue();


		if (__Nod.Rt != NILL)
			createThreadedUtil(__Nod.Rt, q);


		// If the pointer present in the right is NILL, then we have to link it to the in-order successor and then set the whole system to the ‘isThreaded.'
		else {
			if (q.Count != 0)
				__Nod.Rt = q.Peek();
			__Nod.isThreaded = true;
		}
	}
// The function we are creating next is well known for using the populateQueue() and then helps us convert another function called createThreadedUtil() into the binary tree.
	void createThreaded(__Nod __Nod)
	{
		// we have to create another queue that will be known for doing in-order traversal. 
		Queue<__Nod> q = new Queue<__Nod>();


	// Now we have to store the in-order traversal in the queue and wait to observe. 
		populateQueue(__Nod, q);


	//The link we are creating for the right pointers and to fill in for the in-order successor. 
		createThreadedUtil(__Nod, q);
	}


	// Creating a utility function that will help us create the leftmost node in the binary tree, which will have the root, will be specifically used in the in-order traversal.
	__Nod LftMost(__Nod __Nod)
	{
		while (__Nod != NILL && __Nod.Lft != NILL)
			__Nod = __Nod.Lft;
		return __Nod;
	}


// finding out the left-most tree in the binary tree node.
	void inOrder(__Nod __Nod)
	{
		if (__Nod == NILL)
			return;
		__Nod cur = LftMost(__Nod);


		while (cur != NILL) {
			Console.Write(" " + cur.data + " ");


	// If this node is a thread node, then we must travel to an in-order successor. 
			if (cur.isThreaded == true)
				cur = cur.Rt;
			else // Else go to the Leftmost child in Rt subtree
				cur = LftMost(cur.Rt);
		}
	}
// writing the main program to test the functions.
	public static void Main(String[] args)
	{
		BinaryTree tree = new BinaryTree();
		tree.root = new __Nod(1);
		tree.root.Lft = new __Nod(2);
		tree.root.Rt = new __Nod(3);


		tree.root.Lft.Lft = new __Nod(4);
		tree.root.Lft.Rt = new __Nod(5);
		tree.root.Rt.Lft = new __Nod(6);
		tree.root.Rt.Rt = new __Nod(7);


		tree.createThreaded(tree.root);
		Console.WriteLine("Inorder traversal of created threaded tree");
		tree.inOrder(tree.root);
	}
}

Output:

Convert Binary Tree into a Threaded Binary Tree

Example 5)

<script>
/*Writing a Javascript program that will help us change the binary tree into a threaded binary tree and help us transform. */
/*creating a class that will have the left and right child as the current node and will also contain the key value. */
class __Nod
{
	constructor(item)
	{
	// we are using this to see or observe whether the pointer present on the right is a normal one or the pointer is a successor to the in-order one. 
		let isThreaded;
		this.data=item;
		this.Lft = this.Rt = NILL;
		
	}
}


let root;
// creating a new helper function that will help us in putting the nodes in the in-order queue. 
function populateQueue(__Nod,q)
{
	if (__Nod == NILL)
			return;
		if (__Nod.Lft != NILL)
			populateQueue(__Nod.Lft, q);
		q.push(__Nod);
		if (__Nod.Rt != NILL)
			populateQueue(__Nod.Rt, q);
}
// creating a function that will help us visit and traverse the queue and transform the tree into threaded form. 
function createThreadedUtil(__Nod,q)
{
	if (__Nod == NILL)
			return;


		if (__Nod.Lft != NILL)
			createThreadedUtil(__Nod.Lft, q);
		q.shift();


		if (__Nod.Rt != NILL)
			createThreadedUtil(__Nod.Rt, q);


		// If the pointer present in the right is NILL, then we have to link it to the in-order successor and then set the whole system to the ‘isThreaded.'
		else {
			__Nod.Rt = q[0];
			__Nod.isThreaded = true;
		}
}
// The function we are creating next is well known for using the populateQueue() and then helps us convert another function called createThreadedUtil() into the binary tree.
function createThreaded(__Nod)
{
	// we have to create another queue that will be known for doing in-order traversal. 
		let q = [];
// Now we have to store the in-order traversal in the queue and wait to observe. 
		populateQueue(__Nod, q);
//The link we are creating for the right pointers and to fill in for the in-order successor. 
		createThreadedUtil(__Nod, q);
}
// Creating a utility function that will help us create the leftmost node in the binary tree, which will have the root, will be specifically used in the in-order traversal.
function LftMost(__Nod)
{
	while (__Nod != NILL && __Nod.Lft != NILL)
			__Nod = __Nod.Lft;
		return __Nod;
}
// finding out the left-most tree in the binary tree node.
function inOrder(__Nod)
{
	if (__Nod == NILL)
			return;


	// If this node is a thread node, then we must travel to an in-order successor. 
		let cur = LftMost(__Nod);


		while (cur != NILL) {
			document.write(" " + cur.data + " ");


	// On the other hand, we can travel to the left-most child in the right subtree.
			if (cur.isThreaded == true)
				cur = cur.Rt;
			else 
// creating a utility function to create a new node.
				cur = LftMost(cur.Rt);
		}
}
// writing the main program to test the functions
root = new __Nod(1);
		root.Lft = new __Nod(2);
		root.Rt = new __Nod(3);


		root.Lft.Lft = new __Nod(4);
		root.Lft.Rt = new __Nod(5);
		root.Rt.Lft = new __Nod(6);
		root.Rt.Rt = new __Nod(7);


		createThreaded(root);
		
		document. write(
		"In order traversal of created threaded tree<br>"
		);
		inOrder(root);
</script>

Output:

Convert Binary Tree into a Threaded Binary Tree