Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree is a medium trees & bst problem solved with the tree to lists and vice-versa pattern.
The best approach, inorder build with a moving pointer, runs in O(n) time and O(log n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from copy into an array up.
Problem
You are given the head of a singly linked list whose values are sorted in strictly increasing order. Build a height-balanced binary search tree that holds exactly these values and return its root.
Height-balanced means that at every node, the heights of the left and right subtrees differ by at most one. Usually more than one tree fits; any of them is accepted. Trees are shown in level order, with null for a missing child.
Examples
Example 1
- Input
head = [-7, -2, 0, 4, 9]- Output
[0, -7, 4, null, -2, null, 9]- Why
- 0 is the middle value, so it becomes the root. The two values before it form the left subtree and the two after it form the right subtree. Every node's two sides differ in height by at most one.
Example 2
- Input
head = []- Output
[]- Why
- An empty list gives an empty tree.
Example 3
- Input
head = [1, 3]- Output
[1, null, 3]- Why
- With two values, either one can be the root. Here 1 is the root and 3 is its right child; [3, 1] would also be accepted.
Constraints
- The list has
0to2 * 10^4nodes. -10^5 <= Node.val <= 10^5- The values are in strictly increasing order.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Copy into an array | O(n) | O(n) |
| Find the middle with slow and fast pointers | O(n log n) | O(log n) |
| Inorder build with a moving pointer | O(n) | O(log n) |
1Copy into an array
O(n)Copying takes one pass, and every value becomes a node exactly once.O(n)The array holds all n values; the recursion stack adds only O(log n), because each call halves the range.Random access is what makes the sorted-array version easy, so first copy the list into an array. Then the middle of any range is one index away: make it the root, build the left half from the values before it and the right half from the values after it.
- Walk the list once and put every value into an array.
- build(lo, hi): if lo > hi, return null.
- mid = lo + (hi - lo) / 2. Make a node with vals[mid].
- Its left child is build(lo, mid - 1) and its right child is build(mid + 1, hi). Return the node.
class Solution {
private int[] vals;
public TreeNode sortedListToBST(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
vals = new int[n];
int i = 0;
for (ListNode p = head; p != null; p = p.next) vals[i++] = p.val;
return build(0, n - 1);
}
private TreeNode build(int lo, int hi) {
if (lo > hi) return null;
int mid = lo + (hi - lo) / 2;
TreeNode node = new TreeNode(vals[mid]);
node.left = build(lo, mid - 1);
node.right = build(mid + 1, hi);
return node;
}
}class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
vals = []
p = head
while p is not None:
vals.append(p.val)
p = p.next
def build(lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
mid = lo + (hi - lo) // 2
node = TreeNode(vals[mid])
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)
return node
return build(0, len(vals) - 1)class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
vals.clear();
for (ListNode* p = head; p != nullptr; p = p->next) vals.push_back(p->val);
return build(0, (int)vals.size() - 1);
}
private:
vector<int> vals;
TreeNode* build(int lo, int hi) {
if (lo > hi) return nullptr;
int mid = lo + (hi - lo) / 2;
TreeNode* node = new TreeNode(vals[mid]);
node->left = build(lo, mid - 1);
node->right = build(mid + 1, hi);
return node;
}
};function sortedListToBST(head) {
const vals = [];
for (let p = head; p !== null; p = p.next) vals.push(p.val);
const build = (lo, hi) => {
if (lo > hi) return null;
const mid = lo + Math.floor((hi - lo) / 2);
const node = new TreeNode(vals[mid]);
node.left = build(lo, mid - 1);
node.right = build(mid + 1, hi);
return node;
};
return build(0, vals.length - 1);
}2Find the middle with slow and fast pointers
O(n log n)Finding a middle walks half of its piece. On each level of the recursion the pieces together cover the list once, and there are about log n levels.O(log n)No copy of the values, only the recursion stack, which is about log n deep because every piece is split in half.Skip the array and work on the list itself. Describe a piece of the list by its first node and the node just after its end (null for the whole list). A slow pointer that moves one step while a fast pointer moves two stops at the middle of the piece. That middle node is the root; the piece before it and the piece after it become the two subtrees.
- build(start, end) builds the tree for the nodes from start up to, but not including, end. If start == end, the piece is empty: return null.
- Set slow = fast = start. While fast.next != end and fast.next.next != end, move slow one step and fast two steps. Now slow is the middle (the left one when the length is even).
- Make a node with slow.val. Its left child is build(start, slow) and its right child is build(slow.next, end).
- The answer is build(head, null).
class Solution {
public TreeNode sortedListToBST(ListNode head) {
return build(head, null);
}
// builds the nodes from start up to, but not including, end
private TreeNode build(ListNode start, ListNode end) {
if (start == end) return null;
ListNode slow = start, fast = start;
while (fast.next != end && fast.next.next != end) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode node = new TreeNode(slow.val);
node.left = build(start, slow);
node.right = build(slow.next, end);
return node;
}
}class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
return self.build(head, None)
# builds the nodes from start up to, but not including, end
def build(self, start: Optional[ListNode], end: Optional[ListNode]) -> Optional[TreeNode]:
if start is end:
return None
slow = fast = start
while fast.next is not end and fast.next.next is not end:
slow = slow.next
fast = fast.next.next
node = TreeNode(slow.val)
node.left = self.build(start, slow)
node.right = self.build(slow.next, end)
return nodeclass Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return build(head, nullptr);
}
private:
// builds the nodes from start up to, but not including, end
TreeNode* build(ListNode* start, ListNode* end) {
if (start == end) return nullptr;
ListNode* slow = start;
ListNode* fast = start;
while (fast->next != end && fast->next->next != end) {
slow = slow->next;
fast = fast->next->next;
}
TreeNode* node = new TreeNode(slow->val);
node->left = build(start, slow);
node->right = build(slow->next, end);
return node;
}
};function sortedListToBST(head) {
return build(head, null);
}
// builds the nodes from start up to, but not including, end
function build(start, end) {
if (start === end) return null;
let slow = start, fast = start;
while (fast.next !== end && fast.next.next !== end) {
slow = slow.next;
fast = fast.next.next;
}
const node = new TreeNode(slow.val);
node.left = build(start, slow);
node.right = build(slow.next, end);
return node;
}3Inorder build with a moving pointer
O(n)One pass to count, then each list node is read once as the build moves along the list.O(log n)Only the recursion stack, about log n deep, since every range is split in half. The output tree itself is not counted.An inorder walk of a BST (left subtree, node, right subtree) meets the values in sorted order, which is exactly the order of the list. So count the nodes, then build the tree in inorder over the index range 0 to n - 1. Build the whole left half first; by the time it returns, the list pointer has moved past all of its values and points at the value for the current node. Take it, step the pointer forward, then build the right half. No middle is ever searched for.
- Count the nodes: n. Keep a pointer cur at head.
- build(lo, hi): if lo > hi, return null. Let mid = lo + (hi - lo) / 2.
- left = build(lo, mid - 1). This uses up exactly the values that belong left of mid.
- Make a node with cur.val, attach left, and move cur to cur.next.
- node.right = build(mid + 1, hi). Return the node. The answer is build(0, n - 1).
class Solution {
private ListNode cur;
public TreeNode sortedListToBST(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) n++;
cur = head;
return build(0, n - 1);
}
// builds the tree for list positions lo..hi in inorder
private TreeNode build(int lo, int hi) {
if (lo > hi) return null;
int mid = lo + (hi - lo) / 2;
TreeNode left = build(lo, mid - 1);
TreeNode node = new TreeNode(cur.val);
node.left = left;
cur = cur.next;
node.right = build(mid + 1, hi);
return node;
}
}class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
n = 0
p = head
while p is not None:
n += 1
p = p.next
self.cur = head
return self.build(0, n - 1)
# builds the tree for list positions lo..hi in inorder
def build(self, lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
mid = lo + (hi - lo) // 2
left = self.build(lo, mid - 1)
node = TreeNode(self.cur.val)
node.left = left
self.cur = self.cur.next
node.right = self.build(mid + 1, hi)
return nodeclass Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
int n = 0;
for (ListNode* p = head; p != nullptr; p = p->next) n++;
cur = head;
return build(0, n - 1);
}
private:
ListNode* cur = nullptr;
// builds the tree for list positions lo..hi in inorder
TreeNode* build(int lo, int hi) {
if (lo > hi) return nullptr;
int mid = lo + (hi - lo) / 2;
TreeNode* left = build(lo, mid - 1);
TreeNode* node = new TreeNode(cur->val);
node->left = left;
cur = cur->next;
node->right = build(mid + 1, hi);
return node;
}
};function sortedListToBST(head) {
let n = 0;
for (let p = head; p !== null; p = p.next) n++;
let cur = head;
// builds the tree for list positions lo..hi in inorder
const build = (lo, hi) => {
if (lo > hi) return null;
const mid = lo + Math.floor((hi - lo) / 2);
const left = build(lo, mid - 1);
const node = new TreeNode(cur.val);
node.left = left;
cur = cur.next;
node.right = build(mid + 1, hi);
return node;
};
return build(0, n - 1);
}Edge cases to test
- An empty list (return null)
- A single node (a tree with one node)
- Two nodes, where either value may be the root
- An even length, so there are two middle values to choose from
- A long list (20000 nodes), where finding the middle again and again costs extra time
Hints
Hint 1
In a sorted array you would take the middle value as the root and build each half the same way. What makes that hard on a linked list?
Hint 2
You can copy the values into an array first, or find the middle of each piece with a slow and a fast pointer. Both work; one costs memory, the other costs time.
Hint 3
An inorder walk of a BST visits the values in sorted order, which is exactly the order of the list. If you know how many nodes each subtree gets, you can build the tree in inorder and just move along the list as you go.
FAQ
What is the best time complexity for Convert Sorted List to Binary Search Tree?
Inorder build with a moving pointer runs in O(n) time and O(log n) extra space. One pass to count, then each list node is read once as the build moves along the list.
Which pattern does Convert Sorted List to Binary Search Tree use?
It is a trees & bst problem that uses the tree to lists and vice-versa pattern. Other problems with the same pattern: Binary Tree to DLL, Flatten Binary Tree to Linked List.
Is there a brute force solution for Convert Sorted List to Binary Search Tree?
Yes. Copy into an array takes O(n) time and O(n) space. Random access is what makes the sorted-array version easy, so first copy the list into an array.
Which edge cases should I test for Convert Sorted List to Binary Search Tree?
An empty list (return null); A single node (a tree with one node); Two nodes, where either value may be the root; An even length, so there are two middle values to choose from; A long list (20000 nodes), where finding the middle again and again costs extra time.