Skip to problem
←

Convert Sorted Array to Binary Search Tree

Easy 0 attempts

Given a strictly increasing array nums, return the root of a height-balanced binary search tree containing every value exactly once.

For every node, the heights of its left and right subtrees must differ by at most one. There may be several valid trees; return any of them.

Function contract

Implement sortedArrayToBST(nums), where nums is strictly increasing.

Output: A root node with val, left, and right fields containing every input value exactly once. The tree must be a height-balanced BST; any valid shape is accepted. Output is displayed in level order.

Example 1

Input
nums = [-10,-3,0,5,9]
Output
[0,-10,5,null,-3,null,9]

Example 2

Input
nums = [1]
Output
[1]
Constraints
  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in strictly increasing order

Recursive Mid-Point

Pick the middle element as root, recurse on left and right halves.

javascript
function sortedArrayToBST(nums) {
  function build(lo, hi) {
    if (lo > hi) return null;
    const mid = (lo + hi) >> 1;
    return { val: nums[mid], left: build(lo, mid-1), right: build(mid+1, hi) };
  }
  return build(0, nums.length - 1);
}

Time: O(n) | Space: O(log n) auxiliary recursion space, excluding the O(n) returned tree.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript