Convert Sorted List to Binary Search Tree (LeetCode 109): Solution and Explanation
You get the head of a linked list sorted in ascending order. Turn it into a height-balanced binary search tree that holds the same values, where the two subtrees of every node differ in depth by at most one.
Intuition
For a sorted array the classic move is to take the middle value as the root and recurse on each half. With a linked list, reaching the middle costs a walk every time, which pushes the work to O(n log n).
Flip the question around. An inorder traversal of a BST visits values in sorted order, and the list is already in sorted order. So if you create the tree's nodes in inorder, the k-th node you create must hold the k-th list value.
The shape of a balanced tree depends only on how many values there are. Count the list once, recurse over index ranges to decide the shape, and let a single pointer walk the list, handing out the next value each time a node is created.
Approach: Inorder simulation with one list pointer
- Walk the list once to count its length n.
- Set a pointer
currto the head. - Define
build(lo, hi): iflo > hireturn null. Otherwise pickmid = (lo + hi + 1) / 2. - Build the left subtree with
build(lo, mid - 1)first. That call consumes exactly themid - losmallest remaining values. - Create the node from
curr.val, advancecurr, attach the left subtree, then build the right subtree withbuild(mid + 1, hi). - Return
build(0, n - 1).
Step-by-step example
head = [-10,-3,0,5,9]
- Count 5 nodes. build(0, 4) picks mid = 2, so the root slot is index 2, but its value waits until the left side is done.
- build(0, 1) picks mid = 1. Its left call build(0, 0) picks mid = 0, has no children, and takes curr = -10. curr moves to -3.
- Back in build(0, 1): the left side is done, so slot 1 takes -3 with -10 as its left child. curr moves to 0.
- Back in build(0, 4): slot 2 takes 0 as the root. curr moves to 5.
- build(3, 4) picks mid = 4. Its left call fills slot 3 with 5, then slot 4 takes 9. The tree is [0,-3,9,-10,null,5].
Code: Python, Java, C++
1class Solution:
2 def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
3 n = 0
4 node = head
5 while node:
6 n += 1
7 node = node.next
8 self.curr = head
9
10 def build(lo: int, hi: int) -> Optional[TreeNode]:
11 if lo > hi:
12 return None
13 mid = (lo + hi + 1) // 2
14 left = build(lo, mid - 1)
15 root = TreeNode(self.curr.val)
16 self.curr = self.curr.next
17 root.left = left
18 root.right = build(mid + 1, hi)
19 return root
20
21 return build(0, n - 1)1class Solution {
2 private ListNode curr;
3
4 public TreeNode sortedListToBST(ListNode head) {
5 int n = 0;
6 for (ListNode node = head; node != null; node = node.next) {
7 n++;
8 }
9 curr = head;
10 return build(0, n - 1);
11 }
12
13 private TreeNode build(int lo, int hi) {
14 if (lo > hi) return null;
15 int mid = (lo + hi + 1) / 2;
16 TreeNode left = build(lo, mid - 1);
17 TreeNode root = new TreeNode(curr.val);
18 curr = curr.next;
19 root.left = left;
20 root.right = build(mid + 1, hi);
21 return root;
22 }
23}1class Solution {
2 ListNode* curr;
3
4 TreeNode* build(int lo, int hi) {
5 if (lo > hi) return nullptr;
6 int mid = (lo + hi + 1) / 2;
7 TreeNode* left = build(lo, mid - 1);
8 TreeNode* root = new TreeNode(curr->val);
9 curr = curr->next;
10 root->left = left;
11 root->right = build(mid + 1, hi);
12 return root;
13 }
14
15public:
16 TreeNode* sortedListToBST(ListNode* head) {
17 int n = 0;
18 for (ListNode* node = head; node; node = node->next) {
19 n++;
20 }
21 curr = head;
22 return build(0, n - 1);
23 }
24};Time and space complexity
O(n)
The counting walk reads each list node once, and the build creates each tree node once while reading the next list value in O(1).
O(log n)
The recursion depth equals the height of the tree, which is about log n because the tree is balanced. The output tree itself is not counted.
Other approaches
Find the middle with slow and fast pointers (time O(n log n), space O(log n))
For each sublist, use slow and fast pointers to find the middle, make it the root, split the list and recurse on both halves. It is easy to reason about but walks each level of the list again.
Copy the list into an array (time O(n), space O(n))
Copy the values into an array and then build the tree from the array by picking middles directly. It is simple and fast, at the cost of O(n) extra memory.
Common mistakes
- Creating the node before building its left subtree. The left side must consume its smaller values first, otherwise the node takes the wrong value.
- Passing
currby value in languages like Java or C++. The pointer has to be shared across calls, so keep it in a field or a closure. - Forgetting the empty list. With n = 0 the call is build(0, -1), which must return null right away.
- Choosing the middle differently from the expected output and assuming you are wrong. Lower and upper middles both give valid balanced trees.
Frequently asked questions
Why does building in inorder give each node the right value?
An inorder traversal of a BST lists its values in increasing order. The list is also in increasing order, so the k-th node created in inorder must hold the k-th list value. The pointer simply hands them out in sequence.
Why is the result guaranteed to be balanced?
Each call splits its range at the middle, so the left and right ranges differ in size by at most one. The heights of the two subtrees therefore differ by at most one as well.
Why use mid = (lo + hi + 1) / 2 instead of (lo + hi) / 2?
Both are correct. The upper middle reproduces the example output [0,-3,9,-10,null,5]; the lower middle gives [0,-10,5,null,-3,null,9]. Any height-balanced BST with these values is accepted.
Is it cheaper to copy the list into an array first?
It is also O(n) time and often fast in practice, but it uses O(n) extra memory. The inorder build only needs the recursion stack.