Start learning free

LESSON 495 OF 667 · BINARY TREES

Convert Sorted Array to Binary Search Tree in C++: Recursive Midpoint

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.size() <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in a strictly increasing order.
STEP 1 OF 9
    Ctrl + Enter to check

    C++ · BINARY TREES

    Convert Sorted Array To Binary Search Tree in C++, explained

    Problem overview

    The method sortedArrayToBST receives a vector nums sorted in strictly increasing order and returns the root of a binary search tree (BST) holding exactly those values. The tree must be height-balanced: for every node, the heights of its left and right subtrees differ by at most one.

    For nums = [-10, -3, 0, 5, 9] one valid answer has 0 at the root, -10 with a right child -3 on the left, and 5 with a right child 9 on the right. Several trees can be correct, and a different shape that is still balanced and ordered is accepted too. For [1, 3], both 3 with a left child 1, and 1 with a right child 3, are valid.

    Approach: the middle element becomes the root

    A BST needs every value in a node's left subtree to be smaller than the node and every value in its right subtree to be larger. In a sorted array that is easy to satisfy: pick any element as the root, and everything to its left in the array is smaller, everything to its right is larger. The left part then becomes the left subtree, and the right part the right subtree, each built the same way.

    That gives the recursion, but the choice of root decides the balance. If you always pick the first element, every node has only a right child and the tree is a linked list of height n. If you pick the middle element, the two halves differ in size by at most one, and the same holds at every level below. The heights then differ by at most one everywhere, so the tree is balanced.

    Take [1, 2, 3, 4, 5, 6]. The middle index of 0..5 is 2, so the root is 3. The left half [1, 2] has middle index 0, so 1 is the left child, and 2 hangs to its right. The right half [4, 5, 6] has 5 as its root with children 4 and 6.

    Step by step

    1. Delegate in sortedArrayToBST. Call a helper named build with the vector, the first index 0 and the last index nums.size() - 1. Passing index bounds lets every call work on the same vector without copying parts of it.
    2. Declare build. It returns a TreeNode* and takes the vector by reference plus two int parameters, left and right, the inclusive range this call is responsible for.
    3. Base case. If left > right, the range is empty. Return nullptr, which means "no child here". This is what ends the recursion: a one-element range splits into two empty ones.
    4. Find the middle. mid = (left + right) / 2. Integer division drops the fraction, so for an even-sized range this picks the left of the two middle elements.
    5. Create the node with new TreeNode(nums[mid]). It is allocated on the heap because the tree must outlive this function call.
    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 ranges skip mid, because that value is already in node.
    8. Return node so the caller can attach it to its parent. The first call's result is the root of the whole tree.

    The solution in C++

    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return build(nums, 0, nums.size() - 1);
        }
    
        TreeNode* build(vector<int>& nums, int left, int right) {
            if (left > right) {
                return nullptr;
            }
            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;
        }
    };
    

    The C++ details to notice:

    • TreeNode* and new. A local TreeNode object would be destroyed when build returns, leaving the parent with a dangling pointer. new creates the node on the heap, where it stays until it is deleted. Here the caller owns the whole tree. In a real program you would free it with delete or use smart pointers.
    • Arrow syntax. node is a pointer, so its fields are reached with ->. node->left is shorthand for (*node).left.
    • nullptr. It is the type-safe null pointer. A leaf has left and right equal to nullptr, and the base case returns it for every empty range.
    • Pass by reference. The parameter vector<int>& nums avoids copying the vector at each of the roughly n recursive calls. Copying would make the algorithm quadratic.
    • nums.size() - 1. size() returns an unsigned type, and the value is converted to int when it is passed to right. That is fine for sizes up to 10,000. On an empty vector, size() - 1 wraps around to the largest unsigned value, and the conversion to int gives -1 on common platforms. The lesson guarantees at least one element.
    • The midpoint. (left + right) / 2 could overflow int for indices near two billion. With at most 10,000 elements it can't, but left + (right - left) / 2 is the habit that is always safe.
    • Member function order. Inside a class, sortedArrayToBST can call build even though build is defined below it. Member function bodies are compiled once the whole class has been seen.

    Complexity

    Time: O(n). Each call creates exactly one node and then makes two further calls. Every element becomes the middle of exactly one range, so there are n nodes created and n + 1 calls that hit the base case. The work per call is constant.

    Space: O(log n) extra, not counting the tree itself. The recursion goes as deep as the height of the tree, and halving the range each time keeps that near log2(n). The tree has n nodes, which is the output.

    Edge cases and common mistakes

    • A single element. The range 0..0 gives a node with two nullptr children, each coming from a range with left > right.
    • Two elements. For [1, 3] the middle is index 0, so the root is 1 and 3 is its right child. That shape is accepted, and so is the mirror image.
    • Off-by-one in the halves. Recursing on left..mid instead of left..mid - 1 never shrinks a one-element range and the recursion never ends. Skipping mid on both sides is what guarantees progress.
    • Base case with ==. Checking left == right as the stopping case misses the empty ranges that appear when mid is at either end. Use left > right.
    • Slicing the vector. Building new vectors for each half works but copies elements at every level, which costs O(n log n) time. Index bounds avoid it.
    • Choosing the first or last element as the root. The result is still a valid BST, but a chain, so it fails the balance requirement.

    Testing

    Printing the tree in pre-order (node, left, right) with null for a missing child gives these results:

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