Convert Sorted Array to Binary Search Tree
Build a height-balanced BST from a sorted array by always making the middle value the root.
The problem
You get an array nums of distinct integers sorted in increasing order. Build a binary search tree that holds every value and is height-balanced: at every node, the heights of the two subtrees differ by at most 1. Return its root; when several trees qualify, any of them is accepted.
Input nums = [2, 4, 6, 8, 10, 12, 14]
Output [8, 4, 12, 2, 6, 10, 14]
8 is the middle value. 2, 4, 6 form the left subtree with 4 on top, and 10, 12, 14 form the right one with 12 on top.
Input nums = [-7, -1, 3, 9]
Output [-1, -7, 3, null, null, null, 9]
With -1 as the root, -7 goes left and 3, 9 go right. Choosing 3 as the root, which gives [3, -1, 9, -7], is just as correct.
How to spot the pattern
- The input is already sorted, which is exactly the in-order traversal of the BST you have to build.
- Balanced means each root should split the remaining values into two halves of almost equal size.
The idea
In a BST, a node's value sits between everything on its left and everything on its right. If you pick the middle of the sorted array as the root, the values before it become the left subtree and the values after it become the right subtree, and the two sides differ in size by at most 1. Build each half the same way and the whole tree comes out balanced.
Brute force: Insert the values one by one into an ordinary BST, which in sorted order produces a chain of height n and takes O(n^2) time.
Step by step
- 1Write
build(lo, hi), which returns a tree for the valuesnums[lo..hi]. - 2If
lo > hi, the range is empty, so return null. - 3Pick
mid = (lo + hi) / 2and make a node withnums[mid]. - 4Set its left child to
build(lo, mid - 1)and its right child tobuild(mid + 1, hi). - 5Return
build(0, n - 1)as the answer.
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def build(lo: int, hi: int) -> Optional[TreeNode]:
# A balanced BST holding nums[lo..hi].
if lo > hi:
return None
mid = (lo + hi) // 2 # the two halves differ in size by at most 1
return TreeNode(nums[mid], build(lo, mid - 1), build(mid + 1, hi))
return build(0, len(nums) - 1)Complexity
Time
O(n)
Space
O(log n)
Each value becomes exactly one node; the recursion depth is the height of the balanced tree, about log n, on top of the n nodes of the answer itself.
Watch out for
- Slicing the array at every step (
nums[:mid]), which copies values and makes the build O(n log n). - Inserting the sorted values into a BST one at a time: the result is a chain, not a balanced tree.
Follow-up questions
What if the input is a sorted linked list instead of an array?
Finding each middle with slow and fast pointers gives O(n log n). For O(n), count the nodes, then build the tree in in-order order and take list nodes one by one as you go.
Is the answer unique?
No. When a range has an even number of values, either middle value can be its root, and both choices give a balanced BST.
In Hinglish
Sorted array ka beech wala number root banao, left half se left subtree aur right half se right subtree. Har baar beech se todoge toh tree apne aap balanced rahega.