Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Transform a BST to greater sum tree
Next article icon

Sorted Linked List to Balanced BST

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List. 
Examples: 
 

Input:  Linked List 1->2->3
Output: A Balanced BST
2
/ \
1 3


Input: Linked List 1->2->3->4->5->6->7
Output: A Balanced BST
4
/ \
2 6
/ \ / \
1 3 5 7

Input: Linked List 1->2->3->4
Output: A Balanced BST
3
/ \
2 4
/
1

Input: Linked List 1->2->3->4->5->6
Output: A Balanced BST
4
/ \
2 6
/ \ /
1 3 5


Method 1 (Simple) 
Following is a simple algorithm where we first find the middle node of the list and make it the root of the tree to be constructed. 
 

1) Get the Middle of the linked list and make it root.
2) Recursively do same for the left half and right half.
a) Get the middle of the left half and make it left child of the root
created in step 1.
b) Get the middle of right half and make it the right child of the
root created in step 1.
 


Time complexity: O(nLogn) where n is the number of nodes in Linked List.
Method 2 (Tricky) 
Method 1 constructs the tree from root to leaves. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as they appear in Linked List so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we allocate memory for root and link the left subtree with root. Finally, we recursively construct the right subtree and link it with root. 
While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.
 


Following is implementation of method 2. The main code which creates Balanced BST is highlighted. 
 

C++
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std;  /* Link list node */ class LNode  {      public:     int data;      LNode* next;  };   /* A Binary Tree node */ class TNode  {      public:     int data;      TNode* left;      TNode* right;  };   TNode* newNode(int data);  int countLNodes(LNode *head);  TNode* sortedListToBSTRecur(LNode **head_ref, int n);    /* This function counts the number of  nodes in Linked List and then calls  sortedListToBSTRecur() to construct BST */ TNode* sortedListToBST(LNode *head)  {      /*Count the number of nodes in Linked List */     int n = countLNodes(head);       /* Construct BST */     return sortedListToBSTRecur(&head, n);  }   /* The main function that constructs  balanced BST and returns root of it.  head_ref --> Pointer to pointer to  head node of linked list n --> No. of nodes in Linked List */ TNode* sortedListToBSTRecur(LNode **head_ref, int n)  {      /* Base Case */     if (n <= 0)          return NULL;       /* Recursively construct the left subtree */     TNode *left = sortedListToBSTRecur(head_ref, n/2);       /* Allocate memory for root, and      link the above constructed left      subtree with root */     TNode *root = newNode((*head_ref)->data);      root->left = left;       /* Change head pointer of Linked List     for parent recursive calls */     *head_ref = (*head_ref)->next;       /* Recursively construct the right          subtree and link it with root          The number of nodes in right subtree         is total nodes - nodes in          left subtree - 1 (for root) which is n-n/2-1*/     root->right = sortedListToBSTRecur(head_ref, n - n / 2 - 1);       return root;  }     /* UTILITY FUNCTIONS */  /* A utility function that returns  count of nodes in a given Linked List */ int countLNodes(LNode *head)  {      int count = 0;      LNode *temp = head;      while(temp)      {          temp = temp->next;          count++;      }      return count;  }   /* Function to insert a node  at the beginning of the linked list */ void push(LNode** head_ref, int new_data)  {      /* allocate node */     LNode* new_node = new LNode();          /* put in the data */     new_node->data = new_data;       /* link the old list of the new node */     new_node->next = (*head_ref);       /* move the head to point to the new node */     (*head_ref) = new_node;  }   /* Function to print nodes in a given linked list */ void printList(LNode *node)  {      while(node!=NULL)      {          cout << node->data << " ";          node = node->next;      }  }   /* Helper function that allocates a new node with the  given data and NULL left and right pointers. */ TNode* newNode(int data)  {      TNode* node = new TNode();     node->data = data;      node->left = NULL;      node->right = NULL;       return node;  }   /* A utility function to  print preorder traversal of BST */ void preOrder(TNode* node)  {      if (node == NULL)          return;      cout<<node->data<<" ";      preOrder(node->left);      preOrder(node->right);  }   /* Driver code*/ int main()  {      /* Start with the empty list */     LNode* head = NULL;       /* 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 */     TNode *root = sortedListToBST(head);      cout<<"\nPreOrder Traversal of constructed BST ";      preOrder(root);       return 0;  }   // This code is contributed by rathbhupendra 
C
#include<stdio.h> #include<stdlib.h>  /* Link list node */ struct LNode {     int data;     struct LNode* next; };  /* A Binary Tree node */ struct TNode {     int data;     struct TNode* left;     struct TNode* right; };  struct TNode* newNode(int data); int countLNodes(struct LNode *head); struct TNode* sortedListToBSTRecur(struct LNode **head_ref, int n);   /* This function counts the number of nodes in Linked List and then calls    sortedListToBSTRecur() to construct BST */ struct TNode* sortedListToBST(struct LNode *head) {     /*Count the number of nodes in Linked List */     int n = countLNodes(head);      /* Construct BST */     return sortedListToBSTRecur(&head, n); }  /* The main function that constructs balanced BST and returns root of it.        head_ref -->  Pointer to pointer to head node of linked list        n  --> No. of nodes in Linked List */ struct TNode* sortedListToBSTRecur(struct LNode **head_ref, int n) {     /* Base Case */     if (n <= 0)         return NULL;      /* Recursively construct the left subtree */     struct TNode *left = sortedListToBSTRecur(head_ref, n/2);      /* Allocate memory for root, and link the above constructed left         subtree with root */     struct TNode *root = newNode((*head_ref)->data);     root->left = left;      /* Change head pointer of Linked List for parent recursive calls */     *head_ref = (*head_ref)->next;      /* Recursively construct the right subtree and link it with root        The number of nodes in right subtree  is total nodes - nodes in        left subtree - 1 (for root) which is n-n/2-1*/     root->right = sortedListToBSTRecur(head_ref, n-n/2-1);      return root; }    /* UTILITY FUNCTIONS */  /* A utility function that returns count of nodes in a given Linked List */ int countLNodes(struct LNode *head) {     int count = 0;     struct LNode *temp = head;     while(temp)     {         temp = temp->next;         count++;     }     return count; }  /* Function to insert a node at the beginning of the linked list */ void push(struct LNode** head_ref, int new_data) {     /* allocate node */     struct LNode* new_node =         (struct LNode*) malloc(sizeof(struct LNode));     /* put in the data  */     new_node->data  = new_data;      /* link the old list of the new node */     new_node->next = (*head_ref);      /* move the head to point to the new node */     (*head_ref)    = new_node; }  /* Function to print nodes in a given linked list */ void printList(struct LNode *node) {     while(node!=NULL)     {         printf("%d ", node->data);         node = node->next;     } }  /* Helper function that allocates a new node with the    given data and NULL left and right pointers. */ struct TNode* newNode(int data) {     struct TNode* node = (struct TNode*)                          malloc(sizeof(struct TNode));     node->data = data;     node->left = NULL;     node->right = NULL;      return node; }  /* A utility function to print preorder traversal of BST */ void preOrder(struct TNode* node) {     if (node == NULL)         return;     printf("%d ", node->data);     preOrder(node->left);     preOrder(node->right); }  /* Driver program to test above functions*/ int main() {     /* Start with the empty list */     struct LNode* head = NULL;      /* 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 TNode *root = sortedListToBST(head);     printf("\n PreOrder Traversal of constructed BST ");     preOrder(root);      return 0; } 
Java
class LinkedList {      /* head node of link list */     static LNode head;          /* Link list Node */     class LNode      {         int data;         LNode next, prev;          LNode(int d)          {             data = d;             next = prev = null;         }     }          /* A Binary Tree Node */     class TNode      {         int data;         TNode left, right;          TNode(int d)          {             data = d;             left = right = null;         }     }      /* This function counts the number of nodes in Linked List        and then calls sortedListToBSTRecur() to construct BST */     TNode sortedListToBST()      {         /*Count the number of nodes in Linked List */         int n = countNodes(head);          /* Construct BST */         return sortedListToBSTRecur(n);     }      /* The main function that constructs balanced BST and        returns root of it.        n  --> No. of nodes in the Doubly Linked List */     TNode sortedListToBSTRecur(int n)      {         /* Base Case */         if (n <= 0)              return null;          /* Recursively construct the left subtree */         TNode left = sortedListToBSTRecur(n / 2);          /* head_ref now refers to middle node,             make middle node as root of BST*/         TNode root = new TNode(head.data);          // Set pointer to left subtree         root.left = left;          /* Change head pointer of Linked List for parent             recursive calls */         head = head.next;          /* Recursively construct the right subtree and link it             with root. The number of nodes in right subtree  is             total nodes - nodes in left subtree - 1 (for root) */         root.right = sortedListToBSTRecur(n - n / 2 - 1);          return root;     }      /* UTILITY FUNCTIONS */     /* A utility function that returns count of nodes in a         given Linked List */     int countNodes(LNode head)      {         int count = 0;         LNode temp = head;         while (temp != null)         {             temp = temp.next;             count++;         }         return count;     }      /* Function to insert a node at the beginning of         the Doubly Linked List */     void push(int new_data)      {         /* allocate node */         LNode new_node = new LNode(new_data);          /* since we are adding at the beginning,            prev is always NULL */         new_node.prev = null;          /* link the old list of the new node */         new_node.next = head;          /* change prev of head node to new node */         if (head != null)             head.prev = new_node;          /* move the head to point to the new node */         head = new_node;     }      /* Function to print nodes in a given linked list */     void printList(LNode node)      {         while (node != null)          {             System.out.print(node.data + " ");             node = node.next;         }     }      /* A utility function to print preorder traversal of BST */     void preOrder(TNode node)      {         if (node == null)             return;         System.out.print(node.data + " ");         preOrder(node.left);         preOrder(node.right);     }      /* Driver program to test above functions */     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 */         llist.push(7);         llist.push(6);         llist.push(5);         llist.push(4);         llist.push(3);         llist.push(2);         llist.push(1);          System.out.println("Given Linked List ");         llist.printList(head);          /* Convert List to BST */         TNode root = llist.sortedListToBST();         System.out.println("");         System.out.println("Pre-Order Traversal of constructed BST ");         llist.preOrder(root);     } }  // This code has been contributed by Mayank Jaiswal(mayank_24) 
Python3
# Python3 implementation of above approach  # Link list node  class LNode :     def __init__(self):         self.data = None         self.next = None  # A Binary Tree node  class TNode :     def __init__(self):         self.data = None         self.left = None         self.right = None  head = None  # This function counts the number of  # nodes in Linked List and then calls  # sortedListToBSTRecur() to construct BST  def sortedListToBST():      global head          # Count the number of nodes in Linked List      n = countLNodes(head)       # Construct BST      return sortedListToBSTRecur(n)   # The main function that constructs  # balanced BST and returns root of it.  # head -. Pointer to pointer to  # head node of linked list n -. No. # of nodes in Linked List  def sortedListToBSTRecur( n) :     global head          # Base Case      if (n <= 0) :         return None      # Recursively construct the left subtree      left = sortedListToBSTRecur( int(n/2))       # Allocate memory for root, and      # link the above constructed left      # subtree with root      root = newNode((head).data)      root.left = left       # Change head pointer of Linked List     # for parent recursive calls      head = (head).next      # Recursively construct the right      # subtree and link it with root      # The number of nodes in right subtree     # is total nodes - nodes in      # left subtree - 1 (for root) which is n-n/2-1     root.right = sortedListToBSTRecur( n - int(n/2) - 1)       return root   # UTILITY FUNCTIONS   # A utility function that returns  # count of nodes in a given Linked List  def countLNodes(head) :      count = 0     temp = head      while(temp != None):               temp = temp.next         count = count + 1          return count   # Function to insert a node  #at the beginning of the linked list  def push(head, new_data) :      # allocate node      new_node = LNode()          # put in the data      new_node.data = new_data       # link the old list of the new node      new_node.next = (head)       # move the head to point to the new node      (head) = new_node      return head   # Function to print nodes in a given linked list  def printList(node):       while(node != None):               print( node.data ,end= " ")          node = node.next      # Helper function that allocates a new node with the  # given data and None left and right pointers.  def newNode(data) :      node = TNode()     node.data = data      node.left = None     node.right = None      return node   # A utility function to  # print preorder traversal of BST  def preOrder( node) :      if (node == None) :         return     print(node.data, end = " " )     preOrder(node.left)      preOrder(node.right)   # Driver 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)   # This code is contributed by Arnab Kundu 
C#
// C# implementation of above approach using System;      public class LinkedList  {      /* head node of link list */     static LNode head;          /* Link list Node */     class LNode      {         public int data;         public LNode next, prev;          public LNode(int d)          {             data = d;             next = prev = null;         }     }          /* A Binary Tree Node */     class TNode      {         public int data;         public TNode left, right;          public TNode(int d)          {             data = d;             left = right = null;         }     }      /* This function counts the number     of nodes in Linked List and then calls       sortedListToBSTRecur() to construct BST */     TNode sortedListToBST()      {         /*Count the number of nodes in Linked List */         int n = countNodes(head);          /* Construct BST */         return sortedListToBSTRecur(n);     }      /* The main function that constructs      balanced BST and returns root of it.     n --> No. of nodes in the Doubly Linked List */     TNode sortedListToBSTRecur(int n)      {         /* Base Case */         if (n <= 0)              return null;          /* Recursively construct the left subtree */         TNode left = sortedListToBSTRecur(n / 2);          /* head_ref now refers to middle node,          make middle node as root of BST*/         TNode root = new TNode(head.data);          // Set pointer to left subtree         root.left = left;          /* Change head pointer of Linked List          for parent recursive calls */         head = head.next;          /* Recursively construct the           right subtree and link it          with root. The number of          nodes in right subtree is          total nodes - nodes in left         subtree - 1 (for root) */         root.right = sortedListToBSTRecur(n - n / 2 - 1);          return root;     }      /* UTILITY FUNCTIONS */     /* A utility function that returns count       of nodes in a given Linked List */     int countNodes(LNode head)      {         int count = 0;         LNode temp = head;         while (temp != null)         {             temp = temp.next;             count++;         }         return count;     }      /* Function to insert a node at the beginning of      the Doubly Linked List */     void push(int new_data)      {         /* allocate node */         LNode new_node = new LNode(new_data);          /* since we are adding at the beginning,         prev is always NULL */         new_node.prev = null;          /* link the old list of the new node */         new_node.next = head;          /* change prev of head node to new node */         if (head != null)             head.prev = new_node;          /* move the head to point to the new node */         head = new_node;     }      /* Function to print nodes in a given linked list */     void printList(LNode node)      {         while (node != null)          {             Console.Write(node.data + " ");             node = node.next;         }     }      /* A utility function to print      preorder traversal of BST */     void preOrder(TNode node)      {         if (node == null)             return;         Console.Write(node.data + " ");         preOrder(node.left);         preOrder(node.right);     }      /* Driver 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 */         llist.push(7);         llist.push(6);         llist.push(5);         llist.push(4);         llist.push(3);         llist.push(2);         llist.push(1);          Console.WriteLine("Given Linked List ");         llist.printList(head);          /* Convert List to BST */         TNode root = llist.sortedListToBST();         Console.WriteLine("");         Console.WriteLine("Pre-Order Traversal of constructed BST ");         llist.preOrder(root);     } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>   // JavaScript implementation of above approach /* head node of link list */ var head = null;  /* Link list Node */ class LNode  {     constructor(d)     {         this.data = d;         this.next = null;         this.prev = null;     } }  /* A Binary Tree Node */ class TNode  {     constructor(d)     {         this.data = d;         this.left = null;         this.right = null;     } }  /* This function counts the number of nodes in Linked List and then calls   sortedListToBSTRecur() to construct BST */ function sortedListToBST()  {     /*Count the number of nodes in Linked List */     var n = countNodes(head);     /* Construct BST */     return sortedListToBSTRecur(n); } /* The main function that constructs  balanced BST and returns root of it. n --> No. of nodes in the Doubly Linked List */ function sortedListToBSTRecur(n)  {     /* Base Case */     if (n <= 0)          return null;     /* Recursively construct the left subtree */     var left = sortedListToBSTRecur(parseInt(n / 2));     /* head_ref now refers to middle node,      make middle node as root of BST*/     var root = new TNode(head.data);     // Set pointer to left subtree     root.left = left;     /* Change head pointer of Linked List      for parent recursive calls */     head = head.next;     /* Recursively construct the       right subtree and link it      with root. The number of      nodes in right subtree is      total nodes - nodes in left     subtree - 1 (for root) */     root.right = sortedListToBSTRecur(n - parseInt(n / 2) - 1);     return root; } /* UTILITY FUNCTIONS */ /* A utility function that returns count   of nodes in a given Linked List */ function countNodes(head)  {     var count = 0;     var temp = head;     while (temp != null)     {         temp = temp.next;         count++;     }     return count; }  /* Function to insert a node at the beginning of  the Doubly Linked List */ function push( new_data)  {     /* allocate node */     var new_node = new LNode(new_data);     /* since we are adding at the beginning,     prev is always NULL */     new_node.prev = null;     /* link the old list of the new node */     new_node.next = head;     /* change prev of head node to new node */     if (head != null)         head.prev = new_node;     /* move the head to point to the new node */     head = new_node; } /* Function to print nodes in a given linked list */ function printList( node)  {     while (node != null)      {         document.write(node.data + " ");         node = node.next;     } }  /* A utility function to print  preorder traversal of BST */ function preOrder(node)  {     if (node == null)         return;     document.write(node.data + " ");     preOrder(node.left);     preOrder(node.right); }  /* 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
Given Linked List 1 2 3 4 5 6 7   PreOrder Traversal of constructed BST 4 2 1 3 6 5 7

Time Complexity: O(n)

Auxiliary Space: O(logn)

Another Approach(using extra space):
Follow the below steps to solve this problem:
1) Create a array and store all the elements of linked list.
2) Now find the middle element of the linked list and create it root of the tree and call for left array and right array for left and right child.
3) Now recursively repeat above approach until the start becomes greater than end.
4) Now print the preorder traversal of created tree.

Below is the implementation of above approach:

C++
// C++ implementation of above approach #include<bits/stdc++.h> using namespace std;  // link list node struct LNode{      int data;      LNode* next;      LNode(int data){         this->data = data;         this->next = NULL;     } };     // binary tree node struct TNode{      int data;      TNode* left;      TNode* right;      TNode(int data){         this->data = data;         this->left = NULL;         this->right = NULL;     } };  // function to print nodes in a given linked list void printList(LNode* node){     while(node != NULL){         cout<<node->data<<" ";         node = node->next;     } }  void preOrder(TNode* root){     if(root == NULL) return;     cout<<root->data<<" ";     preOrder(root->left);     preOrder(root->right); } TNode* sortedListToBSTRecur(vector<int>& vec, int start, int end){     if(start > end) return NULL;     int mid = start + (end-start)/2;     if((end - start)%2 != 0) mid = mid+1;     TNode* root = new TNode(vec[mid]);     root->left = sortedListToBSTRecur(vec, start, mid-1);     root->right = sortedListToBSTRecur(vec, mid+1, end);     return root; }  TNode* sortedListToBST(LNode* head){     vector<int> vec;     LNode* temp = head;     while(temp != NULL){         vec.push_back(temp->data);         temp = temp->next;     }     return sortedListToBSTRecur(vec, 0, vec.size()-1); }  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     LNode* head = new LNode(1);     head->next = new LNode(2);     head->next->next = new LNode(3);     head->next->next->next = new LNode(4);     head->next->next->next->next = new LNode(5);     head->next->next->next->next->next = new LNode(6);     head->next->next->next->next->next->next = new LNode(7);          cout<<"Given Linked List: "<<endl;     printList(head);     cout<<endl;     // convert list to bst     TNode* root = sortedListToBST(head);     cout<<"Peorder Traversal of constructed BST: "<<endl;     preOrder(root);     return 0; } // THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002) 
Java
// Java implementation of above approach import java.util.*;  // linked list node class LNode {   int data;   LNode next;    LNode(int data) {     this.data = data;     this.next = null;   } }  // binary tree node class TNode {   int data;   TNode left;   TNode right;    TNode(int data) {     this.data = data;     this.left = null;     this.right = null;   } }  public class Main {    // function to print nodes in a given linked list   static void printList(LNode node) {     while (node != null) {       System.out.print(node.data + " ");       node = node.next;     }   }    static void preOrder(TNode root) {     if (root == null) {       return;     }     System.out.print(root.data + " ");     preOrder(root.left);     preOrder(root.right);   }    static TNode sortedListToBSTRecur(List<Integer> vec, int start, int end) {     if (start > end) {       return null;     }     int mid = start + (end - start) / 2;     if ((end - start) % 2 != 0) {       mid = mid + 1;     }     TNode root = new TNode(vec.get(mid));     root.left = sortedListToBSTRecur(vec, start, mid - 1);     root.right = sortedListToBSTRecur(vec, mid + 1, end);     return root;   }    static TNode sortedListToBST(LNode head) {     List<Integer> vec = new ArrayList<Integer>();     LNode temp = head;     while (temp != null) {       vec.add(temp.data);       temp = temp.next;     }     return sortedListToBSTRecur(vec, 0, vec.size() - 1);   }    public static void main(String[] args) {     // Let us create a sorted linked list to test the functions     // Created linked list will be 1->2->3->4->5->6->7     LNode head = new LNode(1);     head.next = new LNode(2);     head.next.next = new LNode(3);     head.next.next.next = new LNode(4);     head.next.next.next.next = new LNode(5);     head.next.next.next.next.next = new LNode(6);     head.next.next.next.next.next.next = new LNode(7);      System.out.println("Given Linked List: ");     printList(head);     System.out.println();     // convert list to bst     TNode root = sortedListToBST(head);     System.out.println("Preorder Traversal of constructed BST: ");     preOrder(root);   } } // This code is contributed by Prajwal Kandekar 
Python
# Python implementation of above approach # link list node class LNode:     def __init__(self, data):         self.data = data         self.next = None             # binary tree node class TNode:     def __init__(self, data):         self.data = data         self.left = None         self.right = None          # function to print nodes in a given linked list def printList(node):     while(node is not None):         print(node.data)         node = node.next      def preOrder(root):     if(root is None):         return     print(root.data)     preOrder(root.left)     preOrder(root.right)      def sortedListToBSTRecur(vec, start, end):     if(start > end):         return None     mid = start + (int)((end-start)/2)     if((end-start)%2 != 0):         mid = mid+1     root = TNode(vec[mid])     root.left = sortedListToBSTRecur(vec, start, mid-1)     root.right = sortedListToBSTRecur(vec, mid+1, end)     return root       def sortedListToBST(head):     vec = []     temp = head     while(temp is not None):         vec.append(temp.data)         temp = temp.next     return sortedListToBSTRecur(vec, 0, len(vec)-1)   # let us create a sorted linked list to test the functions # created linked list will be 1->2->3->4->5->6->7 head = LNode(1) head.next = LNode(2) head.next.next = LNode(3) head.next.next.next = LNode(4) head.next.next.next.next = LNode(5) head.next.next.next.next.next = LNode(6) head.next.next.next.next.next.next = LNode(7)  print("Given Linked List : ") printList(head) print(" ")  # covert list to bst root = sortedListToBST(head) print("PreOrder Traversal of constructed BST : ") preOrder(root) 
C#
using System; using System.Collections.Generic;  // linked list node class LNode {   public int data;   public LNode next;    public LNode(int data) {     this.data = data;     this.next = null;   } }  // binary tree node class TNode {   public int data;   public TNode left;   public TNode right;    public TNode(int data) {     this.data = data;     this.left = null;     this.right = null;   } }  public class MainClass {    // function to print nodes in a given linked list   static void printList(LNode node) {     while (node != null) {       Console.Write(node.data + " ");       node = node.next;     }   }    static void preOrder(TNode root) {     if (root == null) {       return;     }     Console.Write(root.data + " ");     preOrder(root.left);     preOrder(root.right);   }    static TNode sortedListToBSTRecur(List<int> vec, int start, int end) {     if (start > end) {       return null;     }     int mid = start + (end - start) / 2;     if ((end - start) % 2 != 0) {       mid = mid + 1;     }     TNode root = new TNode(vec[mid]);     root.left = sortedListToBSTRecur(vec, start, mid - 1);     root.right = sortedListToBSTRecur(vec, mid + 1, end);     return root;   }    static TNode sortedListToBST(LNode head) {     List<int> vec = new List<int>();     LNode temp = head;     while (temp != null) {       vec.Add(temp.data);       temp = temp.next;     }     return sortedListToBSTRecur(vec, 0, vec.Count - 1);   }    public static void Main(string[] args) {     // Let us create a sorted linked list to test the functions     // Created linked list will be 1->2->3->4->5->6->7     LNode head = new LNode(1);     head.next = new LNode(2);     head.next.next = new LNode(3);     head.next.next.next = new LNode(4);     head.next.next.next.next = new LNode(5);     head.next.next.next.next.next = new LNode(6);     head.next.next.next.next.next.next = new LNode(7);      Console.WriteLine("Given Linked List: ");     printList(head);     Console.WriteLine();          // convert list to bst     TNode root = sortedListToBST(head);     Console.WriteLine("Preorder Traversal of constructed BST: ");     preOrder(root);   } } 
JavaScript
// JavaScript implementation of above approach // link list node class LNode{     constructor(data){         this.data = data;         this.next = null;     } }  // binary tree node class TNode{     constructor(data){         this.data = data;         this.left = null;         this.right = null;     } }  // function to print nodes in a given linked list function printList(node){     while(node != null){         console.log(node.data + " ");         node = node.next;     } }  function preOrder(root){     if(root == null) return;     console.log(root.data + " ");     preOrder(root.left);     preOrder(root.right); }  function sortedListToBSTRecur(vec, start, end){     if(start > end) return null;     let mid = start + (end-start)/2;     if((end-start)%2 != 0) mid = mid+1;     let root = new TNode(vec[mid]);     root.left = sortedListToBSTRecur(vec, start, mid-1);     root.right = sortedListToBSTRecur(vec, mid+1, end);     return root; }  function sortedListToBST(head){     let vec = [];     let temp = head;     while(temp != null){         vec.push(temp.data);         temp = temp.next;     }     return sortedListToBSTRecur(vec, 0, vec.length - 1); }  // Let us create a sorted linked list to test the functions // Created linked list will be 1->2->3->4->5->6->7 let head = new LNode(1); head.next = new LNode(2); head.next.next = new LNode(3); head.next.next.next = new LNode(4); head.next.next.next.next = new LNode(5); head.next.next.next.next.next = new LNode(6); head.next.next.next.next.next.next = new LNode(7);  console.log("Given Linked List: "); printList(head); console.log(" ");  // convert list to bst let root = sortedListToBST(head); console.log("PreOrder Traversal of constructed BST: "); preOrder(root); 

Output
Given Linked List:  1 2 3 4 5 6 7  Peorder Traversal of constructed BST:  4 2 1 3 6 5 7 

Time Complexity: O(N) where N is the number of elements in given linked list.
Auxiliary Space: O(N)



Next Article
Transform a BST to greater sum tree
author
kartik
Improve
Article Tags :
  • Binary Search Tree
  • DSA
  • Linked List
Practice Tags :
  • Binary Search Tree
  • Linked List

Similar Reads

  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
    2 min read
  • Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
  • Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
    10 min read
  • Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output:
    11 min read
  • Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
    10 min read
  • Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences