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.
- The number of nodes in head is in the range [0, 2 * 10⁴].
- -10⁵ <= Node.val <= 10⁵
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
0ton - 1at 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).
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.
Approach
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?
Two ways to solve it
Split positions by count and fill each node from the list as inorder reaches it.
- Reads: each list node once.
- Middle: never searched for.
- Idea: the list order is the inorder order.
The fastest version, and the usual follow-up answer.
Find the middle node with a slow and a fast pointer, make it the root, and recurse on both halves.
- Reads: every level walks its whole range again.
- Middle: found directly, like the array version.
- Idea: easiest to come up with first.
Correct, but a log factor slower.
Both build the same kind of balanced tree; the inorder build reads the list only once, so the steps, code and live demo below use it. The slow and fast pointer version is simpler to invent, and its code comes after the demo.
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.
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 returnNonewithout reading the list.- Otherwise
mid = (l + r) // 2is this subtree's root. The two halves differ in size by at most one, which keeps the tree height-balanced.
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.
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.
Code in Python, C++ and Java
cur starts at the head and will only ever move forward.None and does not move cur: no value is used.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.None and does not move cur: no value is used.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.None and does not move cur: no value is used.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.None and does not move cur: no value is used.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.None and does not move cur: no value is used.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.None and does not move cur: no value is used.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.cur starts at the head and will only ever move forward.None and does not move cur: no value is used.cur already sits on position 0, value 1: the inorder order and the list order match. Make the node, then move cur one step on.None and does not move cur: no value is used.cur now sits on position 1, value 2: the inorder order and the list order match. Make the node, then move cur one step on.None and does not move cur: no value is used.cur already sits on position 2, value 3: the inorder order and the list order match. Make the node, then move cur one step on.None and does not move cur: no value is used.cur already sits on position 3, value 4: the inorder order and the list order match. Make the node, then move cur one step on.None and does not move cur: no value is used.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.n is 0 and the first call is build(0, -1).None: the tree is empty.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.
Common pitfalls
Reading the list before the left subtree is built
root = TreeNode(self.cur.val) self.cur = self.cur.next root.left = build(l, mid - 1)
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
cur = head
def build(l, r):
...
cur = cur.nextself.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.
Edge cases
n = 0, so the first call is build(0, -1), which returns None straight away: an empty tree.
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.
Complexity
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.