Convert Sorted Array to Binary Search Tree - Problem

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than 1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
💡 Note: Middle element 0 becomes root. Left subtree from [-10,-3] has root -3 with left child -10. Right subtree from [5,9] has root 9 with left child 5.
Example 2 — Even Length Array
$ Input: nums = [1,3]
Output: [1,null,3]
💡 Note: For even length, we pick left middle (index 0). Element 1 becomes root with right child 3.
Example 3 — Single Element
$ Input: nums = [0]
Output: [0]
💡 Note: Single element becomes the root with no children.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • nums is sorted in strictly increasing order

Visualization

Tap to expand
Convert Sorted Array to Binary Search Tree INPUT Sorted Array (ascending) -10 -3 0 5 9 [0] [1] [2] [3] [4] Properties - Length: 5 elements - Already sorted Goal Create height-balanced BST where subtree depths differ by at most 1 ALGORITHM STEPS 1 Find Middle mid = (0+4)/2 = 2 nums[2] = 0 (root) 2 Left Subtree Recurse [0,1]: mid=0 nums[0]=-3, child=-10 3 Right Subtree Recurse [3,4]: mid=3 nums[3]=9, child=5 4 Connect Nodes Build tree bottom-up Divide and Conquer 0 -3 9 -10 5 FINAL RESULT Height-Balanced BST 0 -3 9 -10 5 Level-order output: [0,-3,9,-10,null,5] OK - BST property valid OK - Height balanced Key Insight: Choosing the middle element as root guarantees a balanced tree. For a sorted array, the middle element has equal (or nearly equal) elements on both sides, ensuring subtree heights differ by at most 1. Time: O(n), Space: O(log n) for recursion stack. TutorialsPoint - Convert Sorted Array to Binary Search Tree | Optimal Solution
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
311.5K Views
Medium Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen