Start learning free

LESSON 499 OF 671 · BINARY TREES

Convert Sorted Array to BST in JavaScript: Recursive Middle Split

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

    JAVASCRIPT · BINARY TREES

    Convert Sorted Array To Binary Search Tree in JavaScript, explained

    Problem overview

    The method sortedArrayToBST receives nums, an array of integers sorted in strictly ascending order, and returns the root of a height-balanced binary search tree (BST) holding exactly those values. Height-balanced means that for every node, the depths of its left and right subtrees differ by at most one. In a BST, every value in a node's left subtree is smaller than the node's value and every value in its right subtree is larger.

    For [-10, -3, 0, 5, 9] one valid answer has 0 at the root, with -10 and -3 on the left and 5 and 9 on the right. The statement shows it as [0, -10, 5, null, -3, null, 9] in level order. For [1, 3] both [3, 1] and [1, null, 3] are balanced BSTs, so more than one answer can be correct.

    Approach: the middle element becomes the root

    A sorted array already contains the inorder traversal of a BST: reading a BST left subtree, then node, then right subtree gives its values in ascending order. So the job is to choose a root and let the array split itself around it. Everything before the root in the array goes to the left subtree, and everything after it goes to the right.

    The choice of root decides the shape. Take the first element every time and the tree becomes a chain leaning right, with a depth equal to the array length. Take the middle element and the two sides have almost equal sizes. Apply the same rule to each side and every node splits its range roughly in half, so the depths of its two subtrees can differ by at most one.

    The idea is recursive: build the tree for a range by taking its middle element as the root, then building the left subtree from the part on its left and the right subtree from the part on its right. A range with no elements produces no node, which is null.

    The recursion passes two indexes into the same array instead of cutting out smaller arrays with slice. A slice copies its elements, so slicing at every level would copy a lot of data. With indexes, every call shares one array and does constant work of its own.

    Step by step

    1. Start from the main method. sortedArrayToBST calls a helper named build through this.build with the whole array, the first index 0 and the last index, nums.length - 1. Both ends are inclusive.
    2. Declare build(nums, left, right) as a second method of the class. The two indexes mark the part of nums that this call turns into a subtree.
    3. Write the base case. When left > right, the range has no elements. This happens even for non-empty input: when a range has one element, both of its halves are empty.
    4. Return null for the empty range. It means "no node here" and also ends the recursion. Without it, the calls would keep going forever.
    5. Find the middle index. (left + right) / 2 can be fractional in JavaScript, because / does not do integer division. Math.floor rounds it down to a whole index.
    6. Create the node with new TreeNode(nums[mid]). This is the root of the current subtree.
    7. Build the left subtree from left to mid - 1 and assign it to node.left. Every value there is smaller than nums[mid], as the BST rule needs.
    8. Build the right subtree from mid + 1 to right and assign it to node.right. Both ranges skip mid, since that value is already in node.
    9. Return node so the caller can attach the finished subtree to its parent. The first call returns the root of the whole tree.

    On [-10, -3, 0, 5, 9]: the first call has range 0 to 4, so mid = 2 and the root is 0. The left call has range 0 to 1, so mid = 0 and the node is -10, whose left side is empty and whose right side, the range 1 to 1, becomes the node -3. The right call has range 3 to 4, so mid = 3 and the node is 5, with 9 as its right child. That is exactly the tree from the example.

    The solution in JavaScript

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

    JavaScript details worth knowing:

    • Methods call each other through this. Inside a class, writing build(...) alone would look for a variable or a global function named build and fail. Methods of the same object are reached as this.build(...). The recursive calls work because they are written as this.build and are made from a method called on the instance.
    • Math.floor on the midpoint. Indexing an array with a fractional number such as nums[1.5] gives undefined, not an error, so a missing floor would build nodes with undefined values. The sum left + right cannot overflow here: JavaScript numbers are doubles and the indexes are at most 9,999.
    • Which middle is chosen. For an even count the floor picks the left of the two middle elements. That is why [1, 3] gives a root of 1 with 3 as its right child. The statement accepts this shape.
    • TreeNode is supplied. The lesson provides the class, with the value passed to the constructor and left and right starting as null.
    • Returning null explicitly. A function that falls off its end returns undefined, not null. Tree code should return null for "no child" so that all missing children look the same.

    Complexity

    Time: O(n). Every element becomes exactly one node, created in one call of build. Each non-empty call creates one node and makes two more calls, so there are n calls with a node and at most n + 1 calls that hit the empty base case. Each call does constant work, because it passes indexes and copies nothing.

    Space: O(log n) beyond the output. The tree itself takes O(n), but that is the result. The extra memory is the recursion stack, whose depth equals the tree height. Halving the range at each level keeps the height near log₂ n: for 10,000 elements it is 14. A deep stack is never a risk here, which would not be true if the split were uneven.

    Edge cases and common mistakes

    • One element. [7] gives a single node. Both recursive calls get an empty range and return null.
    • Two elements. One of them becomes the root and the other its only child, which is still balanced because the depths differ by one.
    • Off-by-one at the ends. The helper takes inclusive bounds, so the first call must pass nums.length - 1, not nums.length. Passing the length would read nums[nums.length], which is undefined.
    • Including mid in a half. Recursing on left to mid or mid to right repeats a value and, for a one-element range, never shrinks the range, so the recursion never ends.
    • Choosing an end element as the root. It still produces a valid BST, but a chain, and a chain is not height-balanced.
    • Using slice in the recursion. Copying the halves keeps the logic correct but adds an O(n) copy at each level, which turns the total into O(n log n) time.

    Testing

    Level-order lists, with null for missing children:

    • [-10, -3, 0, 5, 9] gives [0, -10, 5, null, -3, null, 9].
    • [1, 3] gives [1, null, 3], one of the two accepted answers.
    • [7] gives [7].
    • [1, 2, 3, 4, 5, 6] gives [3, 1, 5, null, 2, 4, 6].
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free