Skip to content

Convert Sorted Array to Binary Search Tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

InputOutput
nums = [-10,-3,0,5,9]A balanced BST with root 0, left child -3, right child 5
nums = [1,3]A balanced BST with root 3, left child 1
  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in a strictly increasing order.
ApproachTimeSpace
RecursiveO(n)O(log n)
IterativeO(n)O(n)

Space is for recursion stack (recursive) or queue (iterative)

  • Pick Recursive for clarity — divide and conquer pattern is intuitive.
  • Pick Iterative if you prefer avoiding recursion or want explicit queue management.
Intuitive Pattern
Recursive
O(n) time · O(log n) space
Bottom-up Build
Iterative
O(n) time · O(n) space
Section titled “Approach 1: Recursive Divide and Conquer (Recommended)”
★ Recommended
  1. Find the middle element of the current range → becomes the root.
  2. Recursively build the left subtree from the left half.
  3. Recursively build the right subtree from the right half.
  4. Base case: when left > right, return null.
⏱ Time O(n) Visit each node once 💾 Space O(log n) Recursion depth
function sortedArrayToBST(nums):
return build(0, len(nums) - 1)
function build(left, right):
if left > right:
return null
mid = (left + right) / 2
root = TreeNode(nums[mid])
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)
return root
convert_sorted_array_bst_recursive.py
from typing import Optional, List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sortedArrayToBST(nums: List[int]) -> Optional[TreeNode]:
def build(left: int, right: int) -> Optional[TreeNode]:
if left > right:
return None
mid = (left + right) // 2
root = TreeNode(nums[mid])
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)
return root
return build(0, len(nums) - 1)
# Example usage
nums = [-10, -3, 0, 5, 9]
root = sortedArrayToBST(nums)
print(root.val) # 0
print(root.left.val) # -3
print(root.right.val) # 5
🎯 Interview Favourite

Use a queue to track (node, left, right) tuples. Process each node by assigning its value and enqueueing children if ranges are valid.

⏱ Time O(n) Visit each node once 💾 Space O(n) Queue storage
convert_sorted_array_bst_iterative.py
from typing import Optional, List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sortedArrayToBST(nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
root = TreeNode()
queue = deque([(root, 0, len(nums) - 1)])
while queue:
node, left, right = queue.popleft()
mid = (left + right) // 2
node.val = nums[mid]
if left <= mid - 1:
node.left = TreeNode()
queue.append((node.left, left, mid - 1))
if mid + 1 <= right:
node.right = TreeNode()
queue.append((node.right, mid + 1, right))
return root
# Example usage
nums = [-10, -3, 0, 5, 9]
root = sortedArrayToBST(nums)
print(root.val) # 0
print(root.left.val) # -3
print(root.right.val) # 5
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
convert_sorted_array_to_binary_search_tree_space_optimized.py
"""
Solution for Convert Sorted Array to Binary Search Tree
"""
def solve():
"""Implementation for approach 3 of Convert Sorted Array to Binary Search Tree"""
pass
if __name__ == "__main__":
print("Solution ready")