Recursive Mid-Point
Pick the middle element as root, recurse on left and right halves.
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.