Build a balanced BST from a sorted array
Standard · Write code · about 12 min
nums is sorted in increasing order with no repeats. Build a binary search tree of minimum height that holds every value, and return its root.
Use the middle index (lo + hi) / 2, rounded down, of each range as that subtree's root, so the answer is unique.
Example 1
Input:
[[1,2,3,4,5]]
Output:
[3,1,4,null,2,null,5]
3 is the root. Range 0..1 picks index 0, so 1 is the left child and 2 hangs right of it.
Example 2
Input:
[[10,20]]
Output:
[10,null,20]
For two values the lower middle, 10, is the root.
Constraints
- 0 ≤ nums.length ≤ 5,000
- -10,000 ≤ nums[i] ≤ 10,000
- nums is strictly increasing
Learn the idea first: Serialization and construction, a visual lesson.
More Serialization and construction problems
- Serialize a tree to a string Warm-up
- Count distinct encodings Standard
- Serialize and deserialize Standard
- Trace deserialize Standard