# 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);

/* 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. */
{
/*Counting the total number of nodes in a binary tree. */

/* building the new binary search tree. */
}

/* 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. */
{
/* writing the primary case */
if (n <= 0)
return NILL;

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

/* 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->Lft = Lft;

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

/* 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 count = 0;
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.*/
{
/* 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 */

/* locate the head at the new node */
}

/* 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()
{

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

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

return 0;
}
``````

Output: 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);
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. */
{
/*Counting the total number of nodes in a binary tree. */
/* building the new binary search tree. */
}
/* 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
*/
root->Lft = Lft;
/* We have to move ahead and then change the head of the linked list for the parent calls.*/
/* 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*/

return root;
}
/* Creating a brand-new utility function that will most probably return the count of the nodes in a provided linked list */
{
int count = 0;
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 */
/* locate the head at the new node */
}
/* 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()
{

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

/* Convert List to BST */
printf("\n PreOrder Traversal of constructed BST ");
preOrder(root);

return 0;
}
``````

Output: Example 3)

``````class LinkedList {
/* Create the link list node and see its implementation. */
/* 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. */
/* 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
*/

/* 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*/

/* 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 count = 0;
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 */

/* locate the head at the new node */

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

/* 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) {

/* 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);

/* 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: 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

# 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():

# Counting the total number of nodes in a binary tree.

# 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) :

# 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.Lft = Lft

# We must move ahead and then change the head of the linked list for the parent calls.

# 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

count = 0
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.

# 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

# locate the head at the new node
# 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

# Let us create a sorted linked list to test the functions
# Created linked list will be 1.2.3.4.5.6.7

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

Output: Example 5)

``````// creating the #C implementation of the following approach: -
using System;

{
/* 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. */

/* 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);

root.Lft = Lft;

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

/* 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 count = 0;
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 */
/* locate the head at the new node */
}
/* 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)
{

/* let us now create a sorted and balanced function that will help us in the
linked list to test the functions
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);

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

Output: Example 6)

``````<script>

// JavaScript implementation of the above approach

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 */
/* 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*/
// Set pointer to Left subtree
root.Lft = Lft;
for parent recursive calls */
/* Recursively construct the
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 */
{
var count = 0;
while (temp != NILL)
{
temp = temp.next;
count++;
}
return count;
}

/* Function to insert a nod at the beginning of
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 */
/* change prev of a head nod to new nod */
/* move the head to point to the 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
7->6->5->4->3->2->1 */
push(7);
push(6);
push(5);
push(4);
push(3);
push(2);
push(1); 