Problem 109 · LeetCode 109(opens in a new tab)
Convert Sorted List to Binary Search Tree
MediumBinary trees
A singly linked list starts at head, and its values are sorted from smallest to largest. Build a binary search tree that holds exactly those values, and make it height-balanced: at every node, the heights of the left and right subtrees differ by at most 1.
Return the root of the tree. Many trees can qualify; any balanced search tree with these values is accepted.
Example 1
Input: head = [-6, -2, 1, 4, 8] Output: [1, -2, 8, -6, null, 4] Why: 1 is the middle value, two values on each side
2 more examples and the constraints
Example 2
Input: head = [] Output: [] Why: an empty list makes an empty tree
Example 3
Input: head = [3, 7] Output: [7, 3] Why: [3, null, 7] is just as balanced, and also accepted
Constraints
- 0 ≤ number of nodes ≤ 20,000
- −100,000 ≤ each value ≤ 100,000
- The values are in non-decreasing order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy into an arrayO(n)
- Find the middle with two pointersO(n log n)
- Build in sorted orderO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 nodes | Verdict |
|---|---|---|---|
| Copy into an array | O(n) | Passes; uses O(n) memory | |
| Find the middle with two pointers | O(n log n) | Passes; no copy, slower | |
| Build in sorted order | O(n) | Best; one read, no copy |
n = the number of list nodes.
Edge cases to test
- Empty list. head is null: return an empty tree.
- One node. [0] becomes a single root with no children.
- Two nodes. [3, 7] can be 7 over 3 or 3 over 7; both are balanced.
- Repeated values. [6, 6, 6, 6] still works: the in-order walk of the tree must match the list.
Common mistakes
- Choosing the head as the root, which builds a chain instead of a balanced tree.
- Finding the middle without an end bound, so the left half keeps walking into the right half.
- In the in-order build, making the root before building the left subtree, so
curis on the wrong value.
How to talk through it
- 1Clarify. Can the list be empty? Can values repeat? Is any balanced tree accepted?
- 2Start from the array version. Middle is the root, halves recurse. A list cannot index, so copying costs O(n) memory.
- 3Offer two pointers. slow and fast find the middle without a copy, at O(n log n) time.
- 4Build in sorted order. Count, then build left, root from cur, right. Each node is read once.
- 5Test out loud. Run the empty list, one node and [3, 7], then check the heights.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?