Convert Sorted Array to Binary Search Tree (LeetCode 108): Solution and Explanation
You get an array of integers sorted in ascending order and must build a binary search tree from it whose left and right subtrees never differ in height by more than one at any node. Any valid balanced BST is accepted, so there can be several correct outputs.
Watch it run step by step
Try your own input and write the code →Intuition
A sorted array is already the in-order traversal of every BST that holds those values. So the question is not which order the values go in, but which value should sit at the root. If you pick the first element as the root, everything else lands in the right subtree and the tree degenerates into a linked list of height n, which is exactly what the balance rule forbids.
The balance rule pushes you toward the middle. If the root is the middle element, the left half of the array becomes the left subtree and the right half becomes the right subtree, and the two halves differ in size by at most one. Apply the same idea to each half and every node ends up with subtrees of nearly equal size, which keeps the heights within one of each other.
That gives a clean divide and conquer recursion over index ranges. Instead of slicing the array (which copies data), you pass left and right bounds, compute mid, create a node for nums[mid] and recurse on [left, mid - 1] and [mid + 1, right]. An empty range returns None, which is the base case.
Approach: Divide and conquer on the middle element
- Define a helper
build(left, right)that returns the root of a balanced BST built fromnums[left..right]. - If
left > rightthe range is empty, so returnNone. - Compute
mid = (left + right) // 2, the middle index of the range (the left middle when the size is even). - Create a
TreeNodeholdingnums[mid]. - Set
node.lefttobuild(left, mid - 1)andnode.righttobuild(mid + 1, right). - Return the node, and call
build(0, len(nums) - 1)to get the whole tree.
Step-by-step example
nums = [-10, -3, 0, 5, 9]
build(0, 4)picksmid = 2, so the root is 0.- The left call
build(0, 1)picksmid = 0, creating node -10. Its left callbuild(0, -1)returnsNone, and its right callbuild(1, 1)creates node -3. - The right call
build(3, 4)picksmid = 3, creating node 5. Its left range is empty and its right callbuild(4, 4)creates node 9. - The finished tree in level order is
[0, -10, 5, null, -3, null, 9], and every node has subtree heights that differ by at most one.
Code: Python, Java, C++
1class Solution:
2 def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
3 def build(left, right):
4 if left > right:
5 return None
6 mid = (left + right) // 2
7 node = TreeNode(nums[mid])
8 node.left = build(left, mid - 1)
9 node.right = build(mid + 1, right)
10 return node
11 return build(0, len(nums) - 1)1class Solution {
2 int[] nums;
3 public TreeNode sortedArrayToBST(int[] nums) {
4 this.nums = nums;
5 return build(0, nums.length - 1);
6 }
7 private TreeNode build(int left, int right) {
8 if (left > right) return null;
9 int mid = (left + right) / 2;
10 TreeNode node = new TreeNode(nums[mid]);
11 node.left = build(left, mid - 1);
12 node.right = build(mid + 1, right);
13 return node;
14 }
15}1class Solution {
2public:
3 TreeNode* sortedArrayToBST(vector<int>& nums) {
4 return build(nums, 0, nums.size() - 1);
5 }
6 TreeNode* build(vector<int>& nums, int left, int right) {
7 if (left > right) return nullptr;
8 int mid = left + (right - left) / 2;
9 TreeNode* node = new TreeNode(nums[mid]);
10 node->left = build(nums, left, mid - 1);
11 node->right = build(nums, mid + 1, right);
12 return node;
13 }
14};Time and space complexity
O(n)
Every element becomes exactly one node and each call does constant work apart from its two recursive calls, so the total work is linear in the array length.
O(log n)
Ignoring the output tree, the only extra memory is the recursion stack, and because each call halves the range the depth is about log n.
Other approaches
Right middle split (time O(n), space O(log n))
Using (left + right + 1) // 2 picks the right of the two middle elements when the range has even length. It produces a different but equally valid balanced tree, which is why several outputs are accepted.
Iterative build with an explicit stack (time O(n), space O(log n))
You can push (node, left, right) work items onto a stack instead of recursing. It avoids recursion limits in languages with shallow stacks but is longer and harder to read for no asymptotic gain.
Common mistakes
- Slicing the array in each call, as in
build(nums[:mid]), copies data at every level and pushes the time to O(n log n). Pass index bounds instead. - Using
left >= rightas the base case drops single-element ranges, so leaf nodes go missing. - Recursing on
[left, mid]instead of[left, mid - 1]reuses the middle element and can recurse forever on a two-element range. - Computing
mid = (left + right) / 2in Java or C++ with huge bounds can overflow;left + (right - left) / 2is the safe form, although array sizes here are small.
Frequently asked questions
Why pick the middle element as the root?
Choosing the middle splits the remaining values into two halves whose sizes differ by at most one. Doing that recursively keeps every subtree balanced, so the tree has height about log n instead of degrading into a chain.
Is there only one correct answer?
No. When a range has an even number of elements there are two middle candidates, and either choice gives a height-balanced BST. Judges accept any valid balanced tree.
What is the time complexity of converting a sorted array to a BST?
It is O(n) because every element is visited once to create its node. The recursion depth, and therefore the extra space, is O(log n).
How is this different from converting a sorted linked list to a BST?
With an array you can jump straight to the middle in O(1). A linked list needs either a slow and fast pointer walk to find the middle each time, which costs O(n log n), or an in-order simulation that builds the tree while advancing a list pointer in O(n).