AlgoInsight

DSA problem

Convert Sorted List to Binary Search Tree

MediumDivide and ConquerPattern: Divide and Conquertop150FreeAmazonMicrosoftGoogleMetaAppleBloomberg

Given the head of a singly linked list whose elements are sorted in ascending order, convert it to a height-balanced binary search tree. A binary search tree is height-balanced when, for every node, the depths of its two subtrees differ by at most one.

The defining property of a balanced BST built from a sorted sequence is that the root must be (close to) the middle element. Everything to its left becomes the left subtree, everything to its right becomes the right subtree, and the same rule is applied recursively. This is the classic divide-and-conquer recipe: divide the sorted input at its midpoint, conquer each half recursively, and combine by attaching the two recursively built subtrees to the root.

The complication compared to the array version of this problem is random access: a linked list cannot jump to its midpoint in O(1). Two clean techniques handle that. The first finds the middle in each recursive call using the slow/fast two-pointer trick, severing the list before the middle and recursing on the prefix and suffix. This runs in O(n log n) time because each of the log n levels touches O(n) nodes via the slow/fast walk.

A faster O(n) approach precomputes the length, then performs an inorder simulation: it advances a shared list pointer left-to-right while the recursion descends through the implicit balanced tree of indices [0, n-1]. Each list node is visited exactly once, the implicit recursion still produces a tree of height ⌈log₂(n+1)⌉, and the structure is therefore optimal. We show the slow/fast variant as the canonical implementation because it directly mirrors the divide-and-conquer mental model — find the middle, build the tree around it.

Examples

Example 1
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: The middle value 0 becomes the root. The prefix [-10,-3] becomes the left subtree (root -3 with -10 as its left child) and the suffix [5,9] becomes the right subtree (root 9 with 5 as its left child). The resulting tree is height-balanced.
Example 2
Input: head = []
Output: []
Explanation: An empty list yields an empty tree.
Example 3
Input: head = [1,3]
Output: [3,1]
Explanation: The middle of a two-element list (slow/fast picks the second middle) is 3; it becomes the root with 1 attached as its left child. The depths differ by one, which is allowed.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

divide-and-conquerlinked-listtreebinary-search-treerecursion

Browse all DSA problems