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.

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