LeetCode #109 Medium

Convert Sorted List to BST

Convert Sorted List to Binary Search Tree is LeetCode 109 (Medium). You get the head of a singly linked list sorted in ascending order. Build a height-balanced binary search tree from its values and return the root: at every node, the heights of the two subtrees may differ by at most 1.

The list can hold 2 × 10⁴ nodes.

Constraints
  • The number of nodes in head is in the range [0, 2 * 10⁴].
  • -10⁵ <= Node.val <= 10⁵
bstlinked-listdivide-and-conquer
Open on LeetCode ↗
02

Intuition

A balanced BST from sorted values puts the middle value at the root and builds each half the same way. With an array that is easy; a linked list cannot jump to its middle.

The way out: an inorder walk of any BST visits its values in sorted order, which is exactly the order the list already holds. So build the tree in inorder:

  • Shape from counts: split the positions 0 to n - 1 at the middle, as if the list were an array.
  • Values from the list: fill each node at the moment inorder reaches it. That value is always the next unused list node.

The list is read once, front to back, so the whole build is O(n).

How to spot this pattern

Sorted input plus a balanced BST means middle-as-root recursion, as in Convert Sorted Array to Binary Search Tree (108). When the input cannot be indexed, build the tree in inorder and consume the input from the front instead.

03

Approach

Try it first

Before reading on: for a list of 5 nodes, which position becomes the root? When the root's left subtree is finished, how many list nodes has it used, and which node is next?

1

Count the nodes

Walk the list once to get n, then point cur at the head. The tree's shape depends only on n: the recursion splits positions, never values, so it never has to look ahead in the list.

2

Split the range at the middle

build(l, r) builds the subtree for list positions l to r:

  • l > r: there are no positions, so return None without reading the list.
  • Otherwise mid = (l + r) // 2 is this subtree's root. The two halves differ in size by at most one, which keeps the tree height-balanced.
3

Build the left half, then read the list

Call build(l, mid - 1) first. It uses the mid - l smallest values of this range, so when it returns, cur sits on the value at position mid. Make the node from cur.val, move cur one step on, and attach the left subtree.

4

Build the right half and return

build(mid + 1, r) now reads the values after position mid, all larger than the node, so its result is the right child. The first call, build(0, n - 1), returns the root of the whole tree.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
▶3 n, node = 0, head
▶4 while node:
▶5 n += 1
▶6 node = node.next
▶7 self.cur = head
▶8 
▶9 def build(l, r):
▶10 if l > r:
▶11 return None
▶12 mid = (l + r) // 2
▶13 left = build(l, mid - 1)
▶14 root = TreeNode(self.cur.val, left)
▶15 self.cur = self.cur.next
▶16 root.right = build(mid + 1, r)
▶17 return root
▶18 
▶19 return build(0, n - 1)
list-100-31025394curlrmidcounted n = 5 → build(0, 4)
n5
cur-10head of the list
Count first. One walk finds 5 nodes. The tree's shape (grey) depends only on this count, so the build can split positions 0 to 4 like array indices. cur starts at the head and will only ever move forward.
list-100-31025394cur0l4r2midpositions 0–4 → root at position 2
l0
r4
mid2
Range 0–4: its middle position, 2, is this subtree's root, leaving 2 positions on the left and 2 on the right. The node's value is not read yet (dashed): the left subtree must use its smaller values first.
list-100-31025394cur0l1r0midpositions 0–1 → root at position 0
l0
r1
mid0
Range 0–1: its middle position, 0, is this subtree's root, leaving 0 positions on the left and 1 on the right. The node's value is not read yet (dashed): the left subtree must use its smaller values first.
list-100-31025394cur0l-1rmid>l > r (0 > -1) → return None
l0
r-1
The left range of the node at position 0 has no positions (0 > -1), so its left child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur-100l1r0midleft done → take cur = -10 for position 0
mid0
cur-10
node-10position 0
This node has no left subtree, so cur already sits on position 0, value -10: the inorder order and the list order match. Make the node, then move cur one step on.
list-100-31025394cur-101l1r1midpositions 1–1 → root at position 1
l1
r1
mid1
Range 1–1: its middle position, 1, is this subtree's root, leaving 0 positions on the left and 0 on the right. The node's value is not read yet (dashed): the left subtree must use its smaller values first.
list-100-31025394cur-101l0rmid>l > r (1 > 0) → return None
l1
r0
The left range of the node at position 1 has no positions (1 > 0), so its left child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur-10-31l1r1midleft done → take cur = -3 for position 1
mid1
cur-3
node-3position 1
This node has no left subtree, so cur already sits on position 1, value -3: the inorder order and the list order match. Make the node, then move cur one step on.
list-100-31025394cur-10-32l1rmid>l > r (2 > 1) → return None
l2
r1
The right range of -3 has no positions (2 > 1), so its right child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur0-10-30l4r2midleft done → take cur = 0 for position 2
mid2
cur0
node0position 2
The left subtree used exactly 2 values, so cur now sits on position 2, value 0: the inorder order and the list order match. Make the node, then move cur one step on.
list-100-31025394cur0-10-33l4r3midpositions 3–4 → root at position 3
l3
r4
mid3
Range 3–4: its middle position, 3, is this subtree's root, leaving 0 positions on the left and 1 on the right. The node's value is not read yet (dashed): the left subtree must use its smaller values first.
list-100-31025394cur0-10-33l2rmid>l > r (3 > 2) → return None
l3
r2
The left range of the node at position 3 has no positions (3 > 2), so its left child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur0-10-353l4r3midleft done → take cur = 5 for position 3
mid3
cur5
node5position 3
This node has no left subtree, so cur already sits on position 3, value 5: the inorder order and the list order match. Make the node, then move cur one step on.
list-100-31025394cur0-10-354l4r4midpositions 4–4 → root at position 4
l4
r4
mid4
Range 4–4: its middle position, 4, is this subtree's root, leaving 0 positions on the left and 0 on the right. The node's value is not read yet (dashed): the left subtree must use its smaller values first.
list-100-31025394cur0-10-354l3rmid>l > r (4 > 3) → return None
l4
r3
The left range of the node at position 4 has no positions (4 > 3), so its left child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur0-10-3594l4r4midleft done → take cur = 9 for position 4
mid4
cur9
node9position 4
This node has no left subtree, so cur already sits on position 4, value 9: the inorder order and the list order match. Make the node, then move cur one step on.
list-100-31025394cur: end0-10-3595l4rmid>l > r (5 > 4) → return None
l5
r4
The right range of 9 has no positions (5 > 4), so its right child is empty. The call returns None and does not move cur: no value is used.
list-100-31025394cur: end0-10-359lrmidevery list node used once → return root 0
root0
list reads5
Done. cur walked the list once, front to back, and every node got its value in inorder, so the tree is a BST. Each split was at the middle, so the two sides of every node differ in size by at most one: the tree is height-balanced.
05

Slow and fast pointer recursion

build(head, tail) covers the list nodes from head up to, but not including, tail. The fast pointer moves two steps for every one of the slow pointer, so when fast reaches tail, slow is on the middle node: it becomes the root, and the nodes before and after it build the two subtrees.

▶1class Solution:
▶2 def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
▶3 def build(head, tail):
▶4 if head is tail:
▶5 return None
▶6 slow = fast = head
▶7 while fast is not tail and fast.next is not tail:
▶8 slow = slow.next
▶9 fast = fast.next.next
▶10 root = TreeNode(slow.val)
▶11 root.left = build(head, slow)
▶12 root.right = build(slow.next, tail)
▶13 return root
▶14 
▶15 return build(head, None)
06

Common pitfalls

Reading the list before the left subtree is built

✗ Wrong
root = TreeNode(self.cur.val)
self.cur = self.cur.next
root.left = build(l, mid - 1)
✓ Right
left = build(l, mid - 1)
root = TreeNode(self.cur.val, left)
self.cur = self.cur.next

That reads the list in preorder: the root gets the smallest value, not the middle one, and the result is not a BST. For [1, 2, 3] the root becomes 1 with 2 on its left.

Moving a plain local pointer inside the helper

✗ Wrong
cur = head
def build(l, r):
    ...
    cur = cur.next
✓ Right
self.cur = head  # or: nonlocal cur

Assigning to cur inside build makes Python treat it as a new local, so the first read raises UnboundLocalError. Every call must move the same shared pointer, so keep it on self or declare it nonlocal.

07

Edge cases

Empty list

n = 0, so the first call is build(0, -1), which returns None straight away: an empty tree.

Ranges with two middles

A range of even size has two middles, and (l + r) // 2 takes the lower one. So for [-10, -3, 0, 5, 9] this code returns [0,-10,5,null,-3,null,9] while LeetCode prints [0,-3,9,-10,null,5]. Both are balanced, and either is accepted.

08

Complexity

Time
O(n)
Space
O(log n)
One pass counts the nodes and the build reads each list node once. The recursion is as deep as the tree is tall, about log₂ n because the tree is balanced. The n tree nodes are the output, not extra space.
09

Convert Sorted List to BST FAQ

Can I copy the sorted linked list into an array first?

Yes. Copy the values into an array, then build the balanced BST exactly as in Convert Sorted Array to Binary Search Tree (108), taking the middle index as the root. It also runs in O(n) time, but the array costs O(n) extra space, while the inorder build needs only the O(log n) recursion stack.