SDE & MLE Prep

108. Convert Sorted Array to Binary Search Tree

Problem

Turn a sorted array into a height-balanced binary search tree (subtree depths differ by at most 1 at every node). Any such tree is accepted.

Example: [-10,-3,0,5,9] → [0,-3,9,-10,null,5] (or another balanced BST)

Middle element as root keeps the tree height-balanced; recurse on both halves.

Complexity: O(n).

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        def build(lo, hi):
            if lo > hi:
                return None
            mid = (lo + hi) // 2
            return TreeNode(nums[mid], build(lo, mid - 1), build(mid + 1, hi))

        return build(0, len(nums) - 1)