Program to create linked list to binary search tree in Python

A Binary Search Tree (BST) is a tree data structure where each node has at most two children, and for every node, the left subtree contains values smaller than the node, and the right subtree contains values greater than the node. Converting a sorted linked list to a BST involves finding the middle element as the root and recursively building left and right subtrees.

Algorithm

The key insight is to use the two-pointer technique to find the middle node of the linked list ?

  1. Find the middle node using slow and fast pointers
  2. Make the middle node as the root of BST
  3. Recursively build left subtree from nodes before middle
  4. Recursively build right subtree from nodes after middle

Implementation

First, let's define the node classes for linked list and binary tree ?

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

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

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

def print_tree(root):
    if root is not None:
        print_tree(root.left)
        print(root.data, end=', ')
        print_tree(root.right)

class Solution:
    def solve(self, node):
        # Base case: empty list
        if not node:
            return None
        
        # Base case: single node
        if not node.next:
            return TreeNode(node.val)
        
        # Find middle node using two pointers
        slow = fast = node
        prev = None
        
        while fast and fast.next:
            prev = slow
            slow = slow.next
            fast = fast.next.next
        
        # Break the list at middle
        prev.next = None
        
        # Create root with middle element
        root = TreeNode(slow.val)
        
        # Recursively build left and right subtrees
        root.left = self.solve(node)
        root.right = self.solve(slow.next)
        
        return root

# Test the implementation
ob = Solution()
head = make_list([2, 4, 5, 7, 10, 15])
root = ob.solve(head)
print("In-order traversal of BST:")
print_tree(root)
In-order traversal of BST:
2, 4, 5, 7, 10, 15,

Visual Representation

7 4 10 2 5 15

How It Works

The algorithm uses the two-pointer technique where:

  • Slow pointer moves one step at a time
  • Fast pointer moves two steps at a time
  • When fast pointer reaches the end, slow pointer is at the middle
  • The middle element becomes the root to maintain BST balance

Time and Space Complexity

Aspect Complexity Explanation
Time O(n log n) Each level takes O(n) and there are O(log n) levels
Space O(log n) Recursion stack depth

Conclusion

Converting a sorted linked list to a BST involves finding the middle element as root and recursively building subtrees. The two-pointer technique efficiently finds the middle node, resulting in a balanced BST with optimal height.

Updated on: 2026-03-25T11:18:07+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements