Convert Sorted Array to Binary Search Tree

Recursively pick the middle as root — both halves become left and right subtrees.

Easy
Time O(n) Space O(log n)
LeetCode
3 min read
tree bst divide-and-conquer

Problem#

Given an integer array sorted in ascending order, construct a height-balanced BST.

Examples#

  • [-10,-3,0,5,9][0,-3,9,-10,null,5] (any height-balanced answer is accepted).
  • [1,3][3,1].

Constraints#

  • 1 <= nums.length <= 10^4. Strictly increasing.

Approach#

Recurse on [lo, hi]. Pick mid = (lo + hi) / 2 as root; recurse into [lo, mid - 1] for left and [mid + 1, hi] for right.

Solution#

Convert Sorted Array to Binary Search Tree
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
function<TreeNode*(int,int)> build = [&](int lo, int hi) -> TreeNode* {
if (lo > hi) return nullptr;
int mid = lo + (hi - lo) / 2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = build(lo, mid - 1);
node->right = build(mid + 1, hi);
return node;
};
return build(0, nums.size() - 1);
}
};

Editorial#

Choosing the midpoint as root keeps the two halves balanced — depth is O(log n). Inorder traversal of the result recovers the original array, confirming the BST property.

Complexity#

  • Time: O(n).
  • Space: O(log n) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.