Sorted Linked List to Balanced BST

Last Updated : 14 May, 2026

Given a singly linked list of integers increasing order, construct a balanced binary tree that is also a BST, containing the same data members as the linked list.

Examples: 

Input: Linked List : 1->2->3       Output: 2 1 3
Explanation: The BST formed using elements of the linked list is -
       Hence, the preorder traversal of this tree is 2 1 3.

Input: 1 2 3 4 5 6 7

pairwise_swap_of_nodes_in_linkedlistq_1

Output: 4 2 1 3 6 5 7 [Pre-order]

420851421
Try It Yourself
redirect icon

[Naive Approach] Using an Array - O(n) time and O(n) space

The core idea involves converting the linked list into an array. Then, the middle element of this array is used as the root, recursively building a balanced BST.

C++
#include <iostream>
#include <vector>
using namespace std;

class LNode {
public:
	int data;
	LNode* next;
	LNode(int x) {
		data = x;
		next = nullptr;
	}
};

class TNode {
public:
	int data;
	TNode* left;
	TNode* right;
	TNode(int x) {
		data = x;
		left = nullptr;
		right = nullptr;
	}
};

TNode* buildTree(vector<int>& arr, int start, int end) {
	if (start > end) return nullptr;

	int mid = (start + end + 1) / 2;
	TNode* root = new TNode(arr[mid]);

	root->left = buildTree(arr, start, mid - 1);
	root->right = buildTree(arr, mid + 1, end);

	return root;
}

TNode* sortedListToBST(LNode* head) {
	vector<int> arr;

	// Store elements of linked list into array
	while (head) {
		arr.push_back(head->data);
		head = head->next;
	}

	// Build BST from array
	return buildTree(arr, 0, arr.size() - 1);
}

void printTree(TNode* root) {
	if (!root) return;
	cout << root->data << " ";
	printTree(root->left);
	printTree(root->right);
}

int main() {
	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);

	TNode* root = sortedListToBST(head);
	printTree(root);
	return 0;
}
Java
import java.util.ArrayList;

class LNode {
    int data;
    LNode next;
    LNode(int x) {
        data = x;
        next = null;
    }
}

class TNode {
    int data;
    TNode left;
    TNode right;
    TNode(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static TNode buildTree(ArrayList<Integer> arr, int start, int end) {
        if (start > end) return null;

        int mid = (start + end + 1) / 2;
        TNode root = new TNode(arr.get(mid));

        root.left = buildTree(arr, start, mid - 1);
        root.right = buildTree(arr, mid + 1, end);

        return root;
    }

    static TNode sortedListToBST(LNode head) {
        ArrayList<Integer> arr = new ArrayList<>();

        // Store elements of linked list into array
        while (head != null) {
            arr.add(head.data);
            head = head.next;
        }

        // Build BST from array
        return buildTree(arr, 0, arr.size() - 1);
    }

    static void printTree(TNode root) {
        if (root == null) return;
        System.out.print(root.data + " ");
        printTree(root.left);
        printTree(root.right);
    }

    public static void main(String[] args) {
        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);

        TNode root = sortedListToBST(head);
        printTree(root);
    }
}
Python
class LNode:
    def __init__(self, x):
        self.data = x
        self.next = None

class TNode:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def buildTree(arr, start, end):
    if start > end:
        return None

    mid = (start + end + 1) // 2
    root = TNode(arr[mid])

    root.left = buildTree(arr, start, mid - 1)
    root.right = buildTree(arr, mid + 1, end)

    return root

def sortedListToBST(head):
    arr = []

    # Store elements of linked list into array
    while head:
        arr.append(head.data)
        head = head.next

    # Build BST from array
    return buildTree(arr, 0, len(arr) - 1)

def printTree(root):
    if not root:
        return
    print(root.data, end=" ")
    printTree(root.left)
    printTree(root.right)

if __name__ == "__main__":
    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)

    root = sortedListToBST(head)
    printTree(root)
C#
using System;
using System.Collections.Generic;

class LNode {
    
    public int data;
    public LNode next;
    
    public LNode(int x) {
        
        data = x;
        next = null;
    }
}

class TNode {
    
    public int data;
    public TNode left;
    public TNode right;
    
    public TNode(int x) {
        
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static TNode buildTree(List<int> arr, int start, int end) {
        
        if (start > end) return null;

        int mid = (start + end + 1) / 2;
        TNode root = new TNode(arr[mid]);

        root.left = buildTree(arr, start, mid - 1);
        root.right = buildTree(arr, mid + 1, end);

        return root;
    }

    static TNode sortedListToBST(LNode head) {
        List<int> arr = new List<int>();

        // Store elements of linked list into array
        while (head != null) {
            arr.Add(head.data);
            head = head.next;
        }

        // Build BST from array
        return buildTree(arr, 0, arr.Count - 1);
    }

    static void printTree(TNode root) {
        
        if (root == null) return;
        
        Console.Write(root.data + " ");
        
        printTree(root.left);
        printTree(root.right);
    }

    public static void Main(string[] args) {
        
        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);

        TNode root = sortedListToBST(head);
        printTree(root);
    }
}
JavaScript
class LNode {
    
    constructor(x) {
        
        this.data = x;
        this.next = null;
    }
}

class TNode {
    
    constructor(x) {
        
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function buildTree(arr, start, end) {
    
    if (start > end) return null;

    const mid = Math.floor((start + end + 1) / 2);
    const root = new TNode(arr[mid]);

    root.left = buildTree(arr, start, mid - 1);
    root.right = buildTree(arr, mid + 1, end);

    return root;
}

function sortedListToBST(head) {
    
    const arr = [];

    // Store elements of linked list into array
    while (head) {
        
        arr.push(head.data);
        head = head.next;
    }

    // Build BST from array
    return buildTree(arr, 0, arr.length - 1);
}

function printTree(root) {
    
    if (!root) return;
    
    process.stdout.write(root.data + " ");
    
    printTree(root.left);
    printTree(root.right);
}

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

const root = sortedListToBST(head);
printTree(root);

Output
4 2 1 3 6 5 7 

[Expected Approach] In-Order Traversal - O(n) time and O(log n) space

This approach mimics an in-order traversal to construct the tree directly from the linked list. This is achieved by counting the nodes and then recursively building the left subtree, the root, and the right subtree.

C++
#include <iostream>
using namespace std;

class LNode {
public:
	int data;
	LNode* next;
	LNode(int x) {
		data = x;
		next = nullptr;
	}
};

class TNode {
public:
	int data;
	TNode* left;
	TNode* right;
	TNode(int x) {
		data = x;
		left = nullptr;
		right = nullptr;
	}
};

int countNodes(LNode* head) {
	int count = 0;
	while (head) {
		count++;
		head = head->next;
	}
	return count;
}

TNode* buildTree(LNode*& headRef, int n) {
	if (n <= 0) return nullptr;

	// Build left subtree
	TNode* left = buildTree(headRef, n / 2);

	// Create root node
	TNode* root = new TNode(headRef->data);
	root->left = left;

	// Move list head forward
	headRef = headRef->next;

	// Build right subtree
	root->right = buildTree(headRef, n - n / 2 - 1);

	return root;
}

TNode* sortedListToBST(LNode* head) {
	int n = countNodes(head);
	return buildTree(head, n);
}

void printTree(TNode* root) {
	if (!root) return;
	cout << root->data << " ";
	printTree(root->left);
	printTree(root->right);
}

int main() {
	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);

	TNode* root = sortedListToBST(head);
	printTree(root);
	return 0;
}
Java
class LNode {
    int data;
    LNode next;
    LNode(int x) {
        data = x;
        next = null;
    }
}

class TNode {
    int data;
    TNode left;
    TNode right;
    TNode(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static int countNodes(LNode head) {
        int count = 0;
        while (head != null) {
            count++;
            head = head.next;
        }
        return count;
    }

    static TNode buildTree(LNode[] headRef, int n) {
        if (n <= 0) return null;

        // Build left subtree
        TNode left = buildTree(headRef, n / 2);

        // Create root node
        TNode root = new TNode(headRef[0].data);
        root.left = left;

        // Move list head forward
        headRef[0] = headRef[0].next;

        // Build right subtree
        root.right = buildTree(headRef, n - n / 2 - 1);

        return root;
    }

    static TNode sortedListToBST(LNode head) {
        int n = countNodes(head);
        LNode[] headRef = new LNode[]{head};
        return buildTree(headRef, n);
    }

    static void printTree(TNode root) {
        if (root == null) return;
        System.out.print(root.data + " ");
        printTree(root.left);
        printTree(root.right);
    }

    public static void main(String[] args) {
        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);

        TNode root = sortedListToBST(head);
        printTree(root);
    }
}
Python
class LNode:
    def __init__(self, x):
        self.data = x
        self.next = None

class TNode:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def countNodes(head):
    count = 0
    while head:
        count += 1
        head = head.next
    return count

def buildTree(headRef, n):
    if n <= 0:
        return None

    # Build left subtree
    left = buildTree(headRef, n // 2)

    # Create root node
    root = TNode(headRef[0].data)
    root.left = left

    # Move list head forward
    headRef[0] = headRef[0].next

    # Build right subtree
    root.right = buildTree(headRef, n - n // 2 - 1)

    return root

def sortedListToBST(head):
    n = countNodes(head)
    headRef = [head]
    return buildTree(headRef, n)

def printTree(root):
    if not root:
        return
    print(root.data, end=" ")
    printTree(root.left)
    printTree(root.right)

if __name__ == "__main__":
    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)

    root = sortedListToBST(head)
    printTree(root)
C#
using System;

class LNode {
    public int data;
    public LNode next;
    public LNode(int x) {
        data = x;
        next = null;
    }
}

class TNode {
    public int data;
    public TNode left;
    public TNode right;
    public TNode(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static int countNodes(LNode head) {
        int count = 0;
        while (head != null) {
            count++;
            head = head.next;
        }
        return count;
    }

    static TNode buildTree(ref LNode headRef, int n) {
        if (n <= 0) return null;

        // Build left subtree
        TNode left = buildTree(ref headRef, n / 2);

        // Create root node
        TNode root = new TNode(headRef.data);
        root.left = left;

        // Move list head forward
        headRef = headRef.next;

        // Build right subtree
        root.right = buildTree(ref headRef, n - n / 2 - 1);

        return root;
    }

    static TNode sortedListToBST(LNode head) {
        int n = countNodes(head);
        return buildTree(ref head, n);
    }

    static void printTree(TNode root) {
        if (root == null) return;
        Console.Write(root.data + " ");
        printTree(root.left);
        printTree(root.right);
    }

    public static void Main(string[] args) {
        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);

        TNode root = sortedListToBST(head);
        printTree(root);
    }
}
JavaScript
class LNode {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

class TNode {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function countNodes(head) {
    let count = 0;
    while (head) {
        count++;
        head = head.next;
    }
    return count;
}

function buildTree(headRef, n) {
    if (n <= 0) return null;

    // Build left subtree
    let left = buildTree(headRef, Math.floor(n / 2));

    // Create root node
    let root = new TNode(headRef[0].data);
    root.left = left;

    // Move list head forward
    headRef[0] = headRef[0].next;

    // Build right subtree
    root.right = buildTree(headRef, n - Math.floor(n / 2) - 1);

    return root;
}

function sortedListToBST(head) {
    let n = countNodes(head);
    let headRef = [head];
    return buildTree(headRef, n);
}

function printTree(root) {
    if (!root) return;
    process.stdout.write(root.data + " ");
    printTree(root.left);
    printTree(root.right);
}

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

let root = sortedListToBST(head);
printTree(root);

Output
4 2 1 3 6 5 7 
Comment