Algo-Sim › Binary Trees & BST

Convert Sorted Array to Binary Search Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Take the middle value as the root and recurse on each half, so every subtree splits its values evenly and stays height-balanced.

Problem

Given an integer array nums sorted in strictly increasing order, build a height-balanced binary search tree from it (every node’s two subtrees differ in height by at most one). This version always picks the lower middle, so the answer is unique.

Constraints

Edge cases to test

Follow-up questions

What about a sorted linked list?
Build in inorder: recurse on the left half by count, take the current list node as the root, then build the right: O(n) (LC 109).
Why is the result height-balanced?
Each subtree gets half the values (±1), so its height is ⌈log₂(n + 1)⌉.

Solution

Java

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;
}

Python

def sorted_array_to_bst(nums):
    return build(nums, 0, len(nums) - 1)


def build(nums, lo, hi):
    if lo > hi:
        return None
    mid = lo + (hi - lo) // 2
    node = TreeNode(nums[mid])
    node.left = build(nums, lo, mid - 1)
    node.right = build(nums, mid + 1, hi)
    return node

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    TreeNode *sortedArrayToBST(vector<int> &nums) {
        return build(nums, 0, int(nums.size()) - 1);
    }

  private:
    TreeNode *build(vector<int> &nums, int lo, int hi) {
        if (lo > hi)
            return nullptr;
        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;
    }
};

More Binary Trees & BST problems