Convert Sorted Array to BST

Easy BSTDivide and Conquer

Problem

Given a sorted ascending array, return a height-balanced BST built from it.

Example 1 Input: [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5]
Example 2 Input: [1,3] Output: [3,1]

Constraints

Approach — Tree Traversal

This is a Tree Traversal problem. The idea: traverse the tree — DFS recursively, or BFS level by level — and combine the results from each subtree. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time.

Solution code

Python

class Solution:
    def sortedArrayToBST(self, nums):
        def build(lo, hi):
            if lo > hi:
                return None
            mid = (lo + hi) // 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)

Java

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return build(nums, 0, nums.length - 1);
    }
    private TreeNode build(int[] a, int l, int r) {
        if (l > r) return null;
        int m = l + (r - l) / 2;
        TreeNode n = new TreeNode(a[m]);
        n.left  = build(a, l, m - 1);
        n.right = build(a, m + 1, r);
        return n;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Convert Sorted Array to BST interactively → ← All solutions