Convert Sorted Array to BST

EasyTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums sorted in strictly increasing order, build a height-balanced binary search tree containing every element and return its root. Many balanced trees are possible, so this problem fixes one: for a range nums[lo..hi], the root is nums[(lo + hi) // 2] (the **left** of the two middle elements when the range has even length). Build the left subtree from nums[lo..mid-1] and the right subtree from nums[mid+1..hi] with the same rule. The tree is graded in level-order form.

Examples

Input: nums = [-10,-3,0,5,9]
Output: [0,-10,5,null,-3,null,9]
0 is the middle. [-10,-3] picks -10 as its root with -3 on the right; [5,9] picks 5 with 9 on the right.
Input: nums = [1,3]
Output: [1,null,3]
For two elements the left middle, 1, becomes the root.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems