Convert Sorted Array to Binary Search Tree
Recursively pick the middle as root — both halves become left and right subtrees.
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#
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); }};func sortedArrayToBST(nums []int) *TreeNode { var build func(lo, hi int) *TreeNode build = func(lo, hi int) *TreeNode { if lo > hi { return nil } mid := lo + (hi-lo)/2 return &TreeNode{ Val: nums[mid], Left: build(lo, mid-1), Right: build(mid+1, hi), } } return build(0, len(nums)-1)}from typing import List, Optional
# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = right
class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: def build(lo: int, hi: int) -> Optional[TreeNode]: if lo > hi: return None mid = lo + (hi - lo) // 2 node = TreeNode(nums[mid]) node.left = build(lo, mid - 1) node.right = build(mid + 1, hi) return node return build(0, len(nums) - 1)function sortedArrayToBST(nums) { const build = (lo, hi) => { if (lo > hi) return null; const mid = lo + ((hi - lo) >> 1); const node = new TreeNode(nums[mid]); node.left = build(lo, mid - 1); node.right = build(mid + 1, hi); return node; }; return build(0, nums.length - 1);}class Solution { public TreeNode sortedArrayToBST(int[] nums) { return build(nums, 0, nums.length - 1); }
private TreeNode build(int[] nums, int lo, int hi) { if (lo > hi) return null; int mid = lo + (hi - lo) / 2; TreeNode node = new TreeNode(nums[mid]); node.left = build(nums, lo, mid - 1); node.right = build(nums, mid + 1, hi); return node; }}function sortedArrayToBST(nums: number[]): TreeNode | null { const build = (lo: number, hi: number): TreeNode | null => { if (lo > hi) return null; const mid = lo + ((hi - lo) >> 1); const node = new TreeNode(nums[mid]); node.left = build(lo, mid - 1); node.right = build(mid + 1, hi); return node; }; return build(0, nums.length - 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#
Related#