Start learning free

LESSON 499 OF 671 · BINARY TREES

Sorted Array to Balanced BST in Java: Recursive Midpoint Build

Practice Divide and Conquer, O(n) Read the full explanation

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1

Input: nums = [-10,-3,0,5,9]
Output: [0,-10,5,null,-3,null,9]
Explanation: The root is the middle element, 0, and each half is built the same way.
When a part has an even length, the root is the left one of its two middle elements
(-10 for [-10,-3], 5 for [5,9]). [0,-3,9,-10,null,5] is also height-balanced, but the
tests expect the tree above. They print it level by level, with -1 for a missing child:
0 -10 5 -1 -3 -1 9

Example 2

Input: nums = [1,3]
Output: [1,null,3]
Explanation: The root is the left middle element, 1, and 3 is its right child.
[3,1] is also a height-balanced BST, but the tests expect [1,null,3], printed as: 1 -1 3

Constraints

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in a strictly increasing order.
STEP 1 OF 9
    Ctrl + Enter to check

    JAVA · BINARY TREES

    Convert Sorted Array To Binary Search Tree in Java, explained

    Problem overview

    The method sortedArrayToBST receives an int[] named nums, sorted in strictly increasing order, and returns the root of a height-balanced binary search tree holding exactly those values. Height-balanced means that for every node, the heights of its left and right subtrees differ by at most one. A binary search tree keeps smaller values in the left subtree and larger values in the right one.

    For nums = [-10, -3, 0, 5, 9], one valid answer has 0 at the root, -10 and 5 as its children, then -3 under -10 and 9 under 5. Several trees can be correct. For [1, 3], both [3, 1] and [1, null, 3] are balanced, and either shape is acceptable.

    Approach: the middle element is the root

    Because the array is already sorted, an in-order walk of the finished tree must read the values in exactly this order. That settles which values go where once a root is chosen: everything before the root's position goes into its left subtree, and everything after goes into its right subtree.

    The choice of root decides the shape. Always taking the first element would put every other value in the right subtree, producing a chain as deep as the array, which is a valid BST but not a balanced one. Taking the middle element splits the values into two halves whose sizes differ by at most one. Applying the same idea to each half gives subtrees of nearly equal height at every level, so the whole tree is balanced and its height is about log n.

    The recursion is therefore: pick the middle of the current range, make it a node, build the left half as the left child and the right half as the right child. An empty range yields no node.

    On [-10, -3, 0, 5, 9] the middle index is 2, so 0 is the root. The left range [-10, -3] has middle index 0, so -10 becomes its root and -3 its right child. The right range [5, 9] works the same way, with 5 as the root and 9 as its right child.

    Step by step

    1. Call a helper from the main method. sortedArrayToBST passes nums, the first index 0 and the last index nums.length - 1 to build, and returns what it gets back.
    2. Pass index bounds instead of slices. The helper takes left and right to name the part of the array it owns. Every call shares the same array, and no copies are made.
    3. Handle the empty range first. When left > right, the range holds no elements, so the helper returns null. This is what ends the recursion, and it happens often: the halves of a one-element range are both empty.
    4. Find the middle index. (left + right) / 2 uses integer division, which drops the fraction. For a range with an even number of elements this picks the lower of the two middle positions.
    5. Create the node with the value nums[mid].
    6. Build the left subtree from left to mid - 1 and store it in node.left.
    7. Build the right subtree from mid + 1 to right and store it in node.right. Both halves leave out mid, which is already in the node.
    8. Return the node so the caller can attach it to its parent. The first call returns the root of the whole tree.

    The solution in Java

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

    Java details worth a closer look:

    • Why private. Only sortedArrayToBST needs build, so the helper is hidden from other classes. Nothing about the recursion changes if it were public.
    • References and null. TreeNode is a class, so node.left and node.right hold references. A new node starts with both set to null, and returning null from an empty range simply leaves the matching child empty.
    • Arrays are shared, not copied. Passing nums to build passes a reference to the same array, so each recursive call reads the original values. The method never writes to the array.
    • Integer division. In Java, 5 / 2 is 2, and the same holds for non-negative operands like these indices. The expression (left + right) / 2 could overflow int for arrays close to two billion elements. Writing left + (right - left) / 2 avoids that, but with at most 10,000 elements here, the lesson's form is safe.

    Complexity

    Time: O(n). Each element becomes exactly one node, created once. Every call does constant work besides its two recursive calls, and the number of calls is at most 2n + 1: one per node plus one per empty child.

    Space: O(log n) extra, besides the tree itself. The recursion goes as deep as the tree is tall, and the middle choice keeps the height near log n. The tree's own n nodes are the output and aren't counted as extra.

    Edge cases and common mistakes

    • One element. [7] makes a single node. Both recursive calls get an empty range and return null.
    • Two elements. [1, 3] with this midpoint formula gives 1 as the root and 3 as its right child. The mirror-image tree is equally valid.
    • Even-sized ranges. For [1, 2, 3, 4] the lower middle, 2, becomes the root. Its left child is 1 and its right subtree is 3 with 4 as its right child. The heights of the two sides are 1 and 2, which is balanced.
    • Using mid again. Recursing on left to mid or mid to right repeats the middle value and, for a one-element range, never shrinks, so the recursion never ends.
    • Wrong base case. Testing left == right instead of left > right would return null for single-element ranges and lose values.
    • Picking the first or last element as root. The tree would still be a valid BST, but it would be a long chain and not height-balanced.

    Testing

    • [-10, -3, 0, 5, 9] gives the tree [0, -10, 5, null, -3, null, 9].
    • [1, 3] gives [1, null, 3], equally valid as [3, 1].
    • [1, 2, 3, 4] gives [2, 1, 3, null, null, null, 4].
    • [5] gives a single node, [5].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free