Convert Sorted List to Binary Search Tree - Problem

Imagine you have a singly linked list where all elements are arranged in perfect ascending order, like stepping stones across a river. Your mission is to transform this linear structure into a height-balanced binary search tree (BST).

A height-balanced BST is like a well-organized family tree where no branch is significantly longer than others - specifically, the depths of any two leaf nodes differ by at most 1. This ensures optimal search performance with O(log n) operations.

Input: Head of a sorted singly linked list
Output: Root of a height-balanced BST containing the same elements

The challenge lies in efficiently converting the linear structure while maintaining balance without using extra space for array conversion.

Input & Output

example_1.py โ€” Basic Conversion
$ Input: head = [1,2,3,4,5]
โ€บ Output: TreeNode with root=3, left subtree=[1,2], right subtree=[4,5]
๐Ÿ’ก Note: The middle element 3 becomes root. Elements [1,2] form left subtree with 2 as root and 1 as left child. Elements [4,5] form right subtree with 4 as root and 5 as right child.
example_2.py โ€” Even Length
$ Input: head = [1,2,3,4]
โ€บ Output: TreeNode with root=2 or 3 (both valid)
๐Ÿ’ก Note: For even length lists, either middle element can be chosen as root. Most implementations choose the left middle (2), creating balanced BST with equal subtree sizes.
example_3.py โ€” Edge Cases
$ Input: head = [] or head = [1]
โ€บ Output: null or TreeNode(1)
๐Ÿ’ก Note: Empty list returns null. Single node becomes a tree with just root node and no children.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

O(n) to convert list to array + O(n) to build BST = O(n) total

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

O(n) for array storage + O(log n) recursion stack = O(n) total

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in head is in the range [0, 2 * 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • The linked list is guaranteed to be sorted in ascending order
  • Height-balanced means the depth of two leaf nodes should not differ by more than 1
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen