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 Sorted List to Binary Search Tree

Implementation

// creating the C++ implementation of the following approach: -
#include <bits/stdc++.h>
using namespace std;


/* Create the link list node and see its implementation. */
class L__Nod
{
	public:
	int record;
	L__Nod* next;
};


/* constructing a new binary tree node. */
class Tree_Nod
{
	public:
	int record;
	Tree_Nod* Lft;
	Tree_Nod* Rt;
};


Tree_Nod* newNod(int record);
int countL__Nods(L__Nod *head);
Tree_Nod* sortedListToBSTRecur(L__Nod **head_ref, int n);




/* The function created below is responsible for counting all the nodes present in the linked list, and then it perceives the sortedListToBSTRecur() to build a new binary search tree. */
Tree_Nod* sortedListToBST(L__Nod *head)
{
	/*Counting the total number of nodes in a binary tree. */
	int n = countL__Nods(head);


	/* building the new binary search tree. */
	return sortedListToBSTRecur(&head, n);
}


/* The primary function that will build the balanced binary search tree and return the root of the tree is: -
head_ref --> Pointer to a pointer to
the head node of the linked list n --> the number of nodes present in the linked list. */
Tree_Nod* sortedListToBSTRecur(L__Nod **head_ref, int n)
{
	/* writing the primary case */
	if (n <= 0)
		return NILL;


	/* we have recursively built the left subtree. */
	Tree_Nod *Lft = sortedListToBSTRecur(head_ref, n/2);


	/* We have to change the allotment of the memory of the root and then the link of the now manufactured left subtree along with the root
 */
	Tree_Nod *root = newNod((*head_ref)->record);
	root->Lft = Lft;


	/* We have to move ahead and then change the head of the linked list for the parent calls.*/
	*head_ref = (*head_ref)->next;


	/* Now we have to move ahead and build the right subtree, then attach it with the link and root. The number of nodes that will be present in the right subtree will be the same amount of nodes present in the left subtree, which will be - 1 (for root), which is n-n/2-1*/
	root->Rt = sortedListToBSTRecur(head_ref, n - n / 2 - 1);


	return root;
}
/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
int countL__Nods(L__Nod *head)
{
	int count = 0;
	L__Nod *temp = head;
	while(temp)
	{
		temp = temp->next;
		count++;
	}
	return count;
}


/* creating a function that will help us insert the nodes at the beginning and end of the linked list.*/
void push(L__Nod** head_ref, int new_record)
{
	/* allot a node*/
	L__Nod* new_nod = new L__Nod();
	
	/* submit it in the records */
	new_nod->record = new_record;


	/* link the old list of the new nod */
	new_nod->next = (*head_ref);


	/* locate the head at the new node */
	(*head_ref) = new_nod;
}


/* We have to create a function to help print the new linked list. */
void printList(L__Nod *nod)
{
	while(nod!=NILL)
	{
		cout << nod->record << " ";
		nod = nod->next;
	}
}


/* We are creating a new function to help us establish a new node with the given data and fill the null values in the left and right pointers. */
Tree_Nod* newNod(int record)
{
	Tree_Nod* nod = new Tree_Nod();
	nod->record = record;
	nod->Lft = NILL;
	nod->Rt = NILL;


	return nod;
}


/* A utility function to
print preorder traversal of BST */
void preOrder(Tree_Nod* nod)
{
	if (nod == NILL)
		return;
	cout<<nod->record<<" ";
	preOrder(nod->Lft);
	preOrder(nod->Rt);
}


/* writing the main code */
int main()
{
	/* Start with the empty list */
	L__Nod* head = NILL;


	/* Let us create a sorted linked list to test the functions
	Created linked list will be 1->2->3->4->5->6->7 */
	push(&head, 7);
	push(&head, 6);
	push(&head, 5);
	push(&head, 4);
	push(&head, 3);
	push(&head, 2);
	push(&head, 1);


	cout<<"Given Linked List ";
	printList(head);


	/* Convert List to BST */
	Tree_Nod *root = sortedListToBST(head);
	cout<<"\nPreOrder Traversal of constructed BST ";
	preOrder(root);


	return 0;
}

Output:

Convert Sorted List to Binary Search Tree

Example 2)

#include<stdio.h>
#include<stdlib.h>
/* Create the link list node and see its implementation. */
struct L__Nod
{
	int record;
	struct L__Nod* next;
};
/* constructing a new binary tree node. */
struct Tree_Nod
{
	int record;
	struct Tree_Nod* Lft;
	struct Tree_Nod* Rt;
};


struct Tree_Nod* newNod(int record);
int countL__Nods(struct L__Nod *head);
struct Tree_Nod* sortedListToBSTRecur(struct L__Nod **head_ref, int n);


/* The function created below is responsible for counting all the nodes present in the linked list, and then it perceives the sortedListToBSTRecur() to build a new binary search tree. */
struct Tree_Nod* sortedListToBST(struct L__Nod *head)
{
/*Counting the total number of nodes in a binary tree. */
	int n = countL__Nods(head);
/* building the new binary search tree. */
	return sortedListToBSTRecur(&head, n);
}
/* The primary function that will build the balanced binary search tree and return the root of the tree is: -
head_ref --> Pointer to a pointer to
the head node of linked list n --> the number of nodes present in the linked list. */
struct Tree_Nod* sortedListToBSTRecur(struct L__Nod **head_ref, int n)
{
/* writing the basic case */
	if (n <= 0)
		return NILL;
/* we have recursively built the left subtree. */
	struct Tree_Nod *Left = sortedListToBSTRecur(head_ref, n/2);


/* We have to change the allotment of the memory of the root and then the link of the now manufactured left subtree along with the root
 */
	struct Tree_Nod *root = newNod((*head_ref)->record);
	root->Lft = Lft;
/* We have to move ahead and then change the head of the linked list for the parent calls.*/
	*head_ref = (*head_ref)->next;
/* Now we have to move ahead and build the right subtree, then attach it with the link and root. The number of nodes that will be present in the right subtree will be the same amount of nodes present in the left subtree, which will be - 1 (for root), which is n-n/2-1*/
	root->Rt = sortedListToBSTRecur(head_ref, n-n/2-1);


	return root;
}
/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
int countL__Nods(struct L__Nod *head)
{
	int count = 0;
	struct L__Nod *temp = head;
	while(temp)
	{
		temp = temp->next;
		count++;
	}
	return count;
}
/* creating a function that will help us insert the nodes at the beginning and end of the linked list.*/
void push(struct L__Nod** head_ref, int new_record)
{
/* allot a node*/
	struct L__Nod* new_nod =
		(struct L__Nod*) malloc(sizeof(struct L__Nod));
		/* submit it in the records */
	new_nod->record = new_record;
/* link the old list of the new nod */
	new_nod->next = (*head_ref);
	/* locate the head at the new node */
	(*head_ref) = new_nod;
}
/* We have to create a function to help print the new linked list. */
void printList(struct L__Nod *nod)
{
	while(nod!=NILL)
	{
		printf("%d ", nod->record);
		nod = nod->next;
	}
}
/* We are creating a new function to help us establish a new node with the given data and fill the null values in the left and right pointers. */
struct Tree_Nod* newNod(int record)
{
	struct Tree_Nod* nod = (struct Tree_Nod*)
						malloc(sizeof(struct Tree_Nod));
	nod->record = record;
	nod->Lft = NILL;
	nod->Rt = NILL;


	return nod;
}


/* A utility function to print preorder traversal of BST */
void preOrder(struct Tree_Nod* nod)
{
	if (nod == NILL)
		return;
	printf("%d ", nod->record);
	preOrder(nod->Lft);
	preOrder(nod->Rt);
}
/* writing the main code */
int main()
{
	/* Start with the empty list */
	struct L__Nod* head = NILL;


	/* Let us create a sorted linked list to test the functions
	Created linked list will be 1->2->3->4->5->6->7 */
	push(&head, 7);
	push(&head, 6);
	push(&head, 5);
	push(&head, 4);
	push(&head, 3);
	push(&head, 2);
	push(&head, 1);


	printf("\n Given Linked List ");
	printList(head);


	/* Convert List to BST */
	struct Tree_Nod *root = sortedListToBST(head);
	printf("\n PreOrder Traversal of constructed BST ");
	preOrder(root);


	return 0;
}

Output:

Convert Sorted List to Binary Search Tree

Example 3)

class LinkedList {
/* Create the link list node and see its implementation. */
	static L__Nod head;
/* constructing a linked list node. */	
	class L__Nod
	{
		int record;
		L__Nod next, prev;


		L__Nod(int d)
		{
			record = d;
			next = prev = NILL;
		}
	}
/* constructing a new binary tree node. */	
	class Tree_Nod
	{
		int record;
		Tree_Nod Lft, Rt;


		Tree_Nod(int d)
		{
			record = d;
			Lft = Rt = NILL;
		}
	}


	/* The function created below is responsible for counting all the nodes present in the linked list, and then it perceives the sortedListToBSTRecur() to build a new binary search tree. */
	Tree_Nod sortedListToBST()
	{
	/*Counting the total number of nodes in a binary tree. */
		int n = counTree_Nods(head);
/* building the new binary search tree. */
		return sortedListToBSTRecur(n);
	}
/* The primary function that will build the balanced binary search tree and return the root of the tree is: -
head_ref --> Pointer to a pointer to
the head node of the linked list n --> the number of nodes present in the linked list. */
	Tree_Nod sortedListToBSTRecur(int n)
	{
	/* writing the primary case */
		if (n <= 0)
			return NILL;


	/* we have recursively built the left subtree. */
		Tree_Nod Lft = sortedListToBSTRecur(n / 2);


	/* We have to change the allotment of the memory of the root and then the link of the now manufactured left subtree along with the root
 */
		Tree_Nod root = new Tree_Nod(head.record);


		/* We have to move ahead and then change the head of the linked list for the parent calls.*/
		root.Lft = Lft;


		/* Now we have to move ahead and build the right subtree, then attach it with the link and root. The number of nodes that will be present in the right subtree will be the same amount of nodes present in the left subtree, which will be - 1 (for root), which is n-n/2-1*/
		head = head. next;


	/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
		root.Rt = sortedListToBSTRecur(n - n / 2 - 1);


		return root;
	}
/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
	int counTree_Nods(L__Nod head)
	{
		int count = 0;
		L__Nod temp = head;
		while (temp != NILL)
		{
			temp = temp.next;
			count++;
		}
		return count;
	}
/* creating a function that will help us insert the nodes at the beginning and end of the linked list.*/
	void push(int new_record)
	{
		/* allot a node*/
		L__Nod new_nod = new L__Nod(new_record);


		/* submit it in the records */
		new_nod.prev = NILL;


		/* link the old list of the new nod */
		new_nod.next = head;


		/* locate the head at the new node */
		if (head != NILL)
			head.prev = new_nod;


		/* We have to create a function to help print the new linked list. */
		head = new_nod;
	}


/* We are creating a new function to help us establish a new node with the given data and fill the null values in the left and right pointers. */
	void printList(L__Nod nod)
	{
		while (nod != NILL)
		{
			System.out.print(nod.record + " ");
			nod = nod.next;
		}
	}


	/* A utility function to print preorder traversal of BST */
	void preOrder(Tree_Nod nod)
	{
		if (nod == NILL)
			return;
		System.out.print(nod.record + " ");
		preOrder(nod.Lft);
		preOrder(nod.Rt);
	}


	/* writing the main code */
	public static void main(String[] args) {
		LinkedList llist = new LinkedList();


		/* Let us create a sorted linked list to test the functions
		Created linked list will be 7->6->5->4->3->2->1 */
		list.push(7);
		list.push(6);
		list.push(5);
		list.push(4);
		list.push(3);
		list.push(2);
		list.push(1);


		System.out.println("Given Linked List ");
		llist.printList(head);


		/* Convert List to BST */
		Tree_Nod root = list.sortedListToBST();
		System.out.println("");
		System.out.println("Pre-Order Traversal of constructed BST ");
		list.preOrder(root);
	}
}

Output:

Convert Sorted List to Binary Search Tree

Example 4)

# creating the Python implementation of the following approach: -
# Create the link list node and see its implementation. 
class L__Nod :
	def __init__(self):
		self.record = None
		self.next = None


# constructing a new binary tree node
class Tree_Nod :
	def __init__(self):
		self.record = None
		self.Lft = None
		self.Rt = None


head = None


# The function created below is responsible for counting all the nodes present in the linked list, and then it perceives the sortedListToBSTRecur() to build a new binary search tree.
def sortedListToBST():
	global head
	
	# Counting the total number of nodes in a binary tree. 
	n = countL__Nods(head)


	# building the new binary search tree. 
	return sortedListToBSTRecur(n)


#  The primary function that will build the balanced binary search tree and return the root of the tree is: -
head_ref --> Pointer to a pointer to
the head node of the linked list n --> the number of nodes present in the linked list. 
def sortedListToBSTRecur( n) :
	global head
	
	# writing the primary case 
	if (n <= 0) :
		return None


	# We have recursively built the left subtree. 
	Lft = sortedListToBSTRecur( int(n/2))


	# We have to change the allotment of the memory of the root and then the link of the now manufactured left subtree along with the root
	root = newNod((head).record)
	root.Lft = Lft


	# We must move ahead and then change the head of the linked list for the parent calls.
	Head = (head).next


	# Now, we have to move ahead and build the right subtree, then attach it with the link and root. The number of nodes that will be present in the right subtree will be the same amount of nodes present in the left subtree, which will be - 1 (for root), which is n-n/2-1
	root.Rt = sortedListToBSTRecur( n - int(n/2) - 1)


	return root
#  Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list 
def countL__Nods(head) :


	count = 0
	temp = head
	while(temp != None):
	
		temp = temp.next
		count = count + 1
	
	return count


# Creating a function that will help us insert the nodes at the beginning and end of the linked list.
def push(head, new_record) :


	# allot a node
	new_nod = L__Nod()
	
	# Submit it in the records 
	new_nod.record = new_record


	#  link the old list of the new nod 
	new_nod.next = (head)


	# locate the head at the new node 
	(head) = new_nod
	return head
# We have to create a function to help print the new linked list. 
def printList(nod):


	while(nod != None):
	
		print( nod.record ,end= " ")
		nod = nod.next
	
# We are creating a new function to help establish a new node with the given data and fill the null values in the left and right pointers. 
def new(record) :


	nod = Tree_Nod()
	nod.record = record
	nod.Lft = None
	nod.Rt = None


	return nod


# A utility function to
# print preorder traversal of BST
def preOrder( nod) :


	if (nod == None) :
		return
	print(nod.record, end = " " )
	preOrder(nod.Lft)
	preOrder(nod.Rt)


# Writing the main code 
# Start with the empty list
head = None


# Let us create a sorted linked list to test the functions
# Created linked list will be 1.2.3.4.5.6.7
head = push(head, 7)
head = push(head, 6)
head = push(head, 5)
head = push(head, 4)
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)


print("Given Linked List " )
printList(head)


# Convert List to BST
root = sortedListToBST()
print("\nPreOrder Traversal of constructed BST ")
preOrder(root)

Output:

Convert Sorted List to Binary Search Tree

Example 5)

// creating the #C implementation of the following approach: -
using System;
	
public class LinkedList
{
	static L__Nod head;
/* Create the link list node and see its implementation. */
	class L__Nod
	{
		public int record;
		public L__Nod next, prev;


		public L__Nod(int d)
		{
			record = d;
			next = prev = NILL;
		}
	}
/* constructing a new binary tree node. */	
	class Tree_Nod
	{
		public int record;
		public Tree_Nod Lft, Rt;


		public Tree_Nod(int d)
		{
			record = d;
			Lft = Rt = NILL;
		}
	}
/* The function created below is responsible for counting all the nodes present in the linked list, and then it perceives the sortedListToBSTRecur() to build a new binary search tree. */
	Tree_Nod sortedListToBST()
	{
	/*Counting the total number of nodes in a binary tree. */
		int n = counTree_Nods(head);


	/* building the new binary search tree. */
		return sortedListToBSTRecur(n);
	}


	/* The primary function that will build the balanced binary search tree and return the root of the tree is: -
head_ref --> Pointer to a pointer to
the head node of linked list n --> the number of nodes present in the linked list. */
	Tree_Nod sortedListToBSTRecur(int n)
	{
	/* writing the primary case */	
		if (n <= 0)
			return NILL;


		/* we have recursively built the left subtree. */


		Tree_Nod Lft = sortedListToBSTRecur(n / 2);
		Tree_Nod root = new Tree_Nod(head.record);


		root.Lft = Lft;


	/* We have to move ahead and then change the head of the linked list for the parent calls.*/
		head = head.next;


		/* Now we have to move ahead and build the right subtree, then attach it with the link and root. The number of nodes that will be present in the right subtree will be the same amount of nodes present in the left subtree, which will be - 1 (for root), which is n-n/2-1*/
		root.Rt = sortedListToBSTRecur(n - n / 2 - 1);


		return root;
	}
/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
	int counTree_Nods(L__Nod head)
	{
		int count = 0;
		L__Nod temp = head;
		while (temp != NILL)
		{
			temp = temp.next;
			count++;
		}
		return count;
	}


	/* creating a function that will help us insert the nodes at the beginning and end of the linked list.*/
	void push(int new_record)
	{
		/* allot a node*/
		L__Nod new_nod = new L__Nod(new_record);


/* submit it in the records */
		new_nod.prev = NILL;


		/* link the old list of the new nod */
		new_nod.next = head;
		if (head != NILL)
			head.prev = new_nod;
/* locate the head at the new node */
		head = new_nod;
	}
/* We have to create a function to help print the new linked list. */
	void printList(L__Nod nod)
	{
		while (nod != NILL)
		{
			Console.Write(nod.record + " ");
			nod = nod.next;
		}
	}
/* We are creating a new function to help us establish a new node with the given data and fill the null values in the left and right pointers. */
	/* creating a function that will help us print the pre-order traversal of the binary search tree. */
	void preOrder(Tree_Nod nod)
	{
		if (nod == NILL)
			return;
		Console.Write(nod.record + " ");
		preOrder(nod.Lft);
		preOrder(nod.Rt);
	}
/* writing the main code */
	public static void Main(String[] args)
	{
		LinkedList llist = new LinkedList();


		/* let us now create a sorted and balanced function that will help us in the
		linked list to test the functions
		Created linked list will be
		7->6->5->4->3->2->1 */
		list.push(7);
		list.push(6);
		list.push(5);
		list.push(4);
		list.push(3);
		list.push(2);
		list.push(1);


		Console.WriteLine("Given Linked List ");
		llist.printList(head);


		/* Convert List to BST */
		Tree_Nod root = list.sortedListToBST();
		Console.WriteLine(");
		Console.WriteLine("Pre-Order Traversal of constructed BST ");
		list.preOrder(root);
	}
}

Output:

Convert Sorted List to Binary Search Tree

Example 6)

<script>


// JavaScript implementation of the above approach
/* head nod of link list */
var head = NILL;


/* Link list Nod */
class L__Nod
{
	constructor(d)
	{
		this.record = d;
		this.next = NILL;
		this.prev = NILL;
	}
}


/* A Binary Tree Nod */
class Tree_Nod
{
	constructor(d)
	{
		this.record = d;
		this.Lft = NILL;
		this.Rt = NILL;
	}
}


/* This function counts the number
of nods in Linked List and then calls
sortedListToBSTRecur() to construct BST */
function sortedListToBST()
{
	/*Count the number of nods in Linked List */
	var n = counTree_Nods(head);
	/* Construct BST */
	return sortedListToBSTRecur(n);
}
/* The main function constructs
balanced BST and returns the root of it.
n --> No. of nods in the Doubly Linked List */
function sortedListToBSTRecur(n)
{
	/* Base Case */
	if (n <= 0)
		return NILL;
	/* Recursively construct the Left subtree */
	var Lft = sortedListToBSTRecur(parseInt(n / 2));
	/* head_ref now refers to the middle nod,
	make the middle nod the root of BST*/
	var root = new Tree_Nod(head.record);
	// Set pointer to Left subtree
	root.Lft = Lft;
	/* Change the head pointer of the Linked List
	for parent recursive calls */
	head = head.next;
	/* Recursively construct the
	Rt subtree and link it
	with root. The number of
	nods in Rt subtree is
	total nods - nods in Lft
	subtree - 1 (for root) */
	root.Rt = sortedListToBSTRecur(n - parseInt(n / 2) - 1);
	return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns the count
of nods in a given Linked List */
function counTree_Nods(head)
{
	var count = 0;
	var temp = head;
	while (temp != NILL)
	{
		temp = temp.next;
		count++;
	}
	return count;
}


/* Function to insert a nod at the beginning of
the Doubly Linked List */
function push( new_record)
{
	/* allocate nod */
	var new_nod = new L__Nod(new_record);
	/* since we are adding at the beginning,
	prev is always NILL */
	new_nod.prev = NILL;
	/* link the old list of the new nod */
	new_nod.next = head;
	/* change prev of a head nod to new nod */
	if (head != NILL)
		head.prev = new_nod;
	/* move the head to point to the new nod */
	head = new_nod;
}
/* Function to print nods in a given linked list */
function printList( nod)
{
	while (nod != NILL)
	{
		document.write(nod.record + " ");
		nod = nod.next;
	}
}


/* A utility function to print
preorder traversal of BST */
function preOrder(nod)
{
	if (nod == NILL)
		return;
	document.write(nod.record + " ");
	preOrder(nod.Lft);
	preOrder(nod.Rt);
}


/* Driver code */


/* Let us create a sorted
linked list to test the functions
Created linked list will be
7->6->5->4->3->2->1 */
push(7);
push(6);
push(5);
push(4);
push(3);
push(2);
push(1);
document.write("Given Linked List ");
printList(head);
/* Convert List to BST */
var root = sortedListToBST();
document.write("<br>");
document.write("Pre-Order Traversal of constructed BST ");
preOrder(root);


</script>

Output:

Convert Sorted List to Binary Search Tree