Start learning free

LESSON 501 OF 673 · BINARY TREES

Convert Sorted Array to Binary Search Tree in Python: Recursion

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,None,-3,None,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,None,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,None,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,None,3], printed as: 1 -1 3

Constraints

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

    PYTHON · BINARY TREES

    Convert Sorted Array To Binary Search Tree in Python, explained

    Problem overview

    The method sortedArrayToBST receives a list nums of integers sorted in strictly increasing order. It must return the root of a height-balanced binary search tree that holds exactly those values. Height-balanced means that for every node, the heights of its left and right subtrees differ by at most one.

    In the first example, nums = [-10, -3, 0, 5, 9]. One valid answer has 0 at the root, with -10 and 5 below it, and -3 and 9 below those. Its level-order form is [0, -10, 5, None, -3, None, 9]. Other balanced trees are accepted too, such as [0, -3, 9, -10, None, 5], because many shapes satisfy the rules. In the second example, [1, 3], either value can be the root.

    Approach: the middle element becomes the root

    A binary search tree keeps smaller values in the left subtree and larger values in the right subtree. Because nums is already sorted, every value before a given position is smaller than the value at that position, and every value after it is larger. So if you pick any element as the root, the elements to its left in the list must form the left subtree, and the elements to its right must form the right subtree. The ordering rule is satisfied automatically.

    What decides the balance is which element you pick. Choosing the first or last element puts everything on one side and produces a chain, a tree as tall as the list is long. Choosing the middle element splits the rest into two halves of nearly equal size. Do the same inside each half, and every node has two subtrees whose sizes differ by at most one, which keeps their heights within one of each other as well.

    This is a natural recursion: build a tree from a range of the list by choosing its middle element, then build the left subtree from the part before it and the right subtree from the part after it. A range with no elements produces no node, which is the base case.

    The lesson passes the range as two indices, left and right, instead of slicing the list. A slice such as nums[:mid] copies its elements, so slicing at every level would copy the list again and again. With indices, every call reads the same list.

    Step by step

    1. Start the recursion from sortedArrayToBST. It calls the helper build with the whole list: start index 0 and last index len(nums) - 1. Both bounds are inclusive.
    2. Define build with the range as parameters. left and right say which part of nums this call is responsible for. Because build is a method, it is called as self.build(...), including in the recursive calls.
    3. Stop on an empty range. When left > right there are no elements left, so the call returns None. This case occurs even for a non-empty input: a range holding one element splits into two empty ranges.
    4. Find the middle index as (left + right) // 2. The // operator divides and rounds down, so mid is a whole number you can use as a list index.
    5. Create the node from nums[mid]. This is the root of the subtree for this range.
    6. Build the left subtree from left to mid - 1 and attach it as node.left.
    7. Build the right subtree from mid + 1 to right and attach it as node.right. Both ranges skip mid, because that value is already in node.
    8. Return node so the caller can attach it to its own parent. The first call returns the root of the whole tree.

    The solution in Python

    class Solution:
        def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
            return self.build(nums, 0, len(nums) - 1)
    
        def build(self, nums, left, right):
            if left > right:
                return None
            mid = (left + right) // 2
            node = TreeNode(nums[mid])
            node.left = self.build(nums, left, mid - 1)
            node.right = self.build(nums, mid + 1, right)
            return node
    

    The Python details worth a closer look:

    • Floor division picks the left middle. For a range of even length, there are two middle positions. With left = 0 and right = 1, (0 + 1) // 2 is 0, so the lower one is the root. For [1, 3] the result is the tree [1, None, 3], which the statement lists as valid. Using plain / would produce a float such as 0.5, and a list index must be an integer, so it would raise a TypeError.
    • No overflow worry. Python integers have no fixed size, so left + right can't overflow. Languages with fixed-width integers sometimes write left + (right - left) // 2 instead.
    • A TreeNode is an ordinary object. Its constructor takes the value, and left and right start as None. Assigning to node.left and node.right afterwards links the children.
    • Self-calls need self. Inside a class, build(nums, ...) on its own would raise a NameError. The method is reached through the instance, as self.build.
    • The return type. Optional[TreeNode] means the result is a TreeNode or None. The helper returns None for an empty range, and that value becomes a missing child.

    Complexity

    Time: O(n). Each element is the middle of exactly one range, so build creates exactly one node per element. The calls that return None do constant work, and there are n + 1 of them. The total is proportional to n.

    Space: O(log n) extra, not counting the tree. The tree itself needs n nodes, which the task requires. Besides that, the only memory is the recursion stack. Each call halves the range, so the depth is about log2(n). For 10,000 elements that is around 14 levels, far below Python's default recursion limit of 1000. Slicing instead of using indices would add O(n) copying work per level.

    Edge cases and common mistakes

    • One element. [7] makes a single node with no children: both recursive calls get an empty range and return None.
    • Two elements. One value becomes the root and the other its only child. Both choices are balanced.
    • Using left >= right as the base case. A range with one element has left == right, so that element would be dropped. Only left > right means the range is empty.
    • Including mid again. Calling build(nums, left, mid) would never shrink a one-element range, and the recursion would not end.
    • Picking an end element. Always choosing left as the root makes a valid BST, but it is a chain of length n, not a balanced tree.
    • Several correct answers. A tree different from the one in an example can still be right. For six elements, this solution gives [3, 1, 5, None, 2, 4, 6] in level order. Check the properties (sorted in-order values, heights within one), not one fixed shape.

    Testing

    • nums = [-10, -3, 0, 5, 9] gives level order [0, -10, 5, None, -3, None, 9].
    • nums = [1, 3] gives [1, None, 3].
    • nums = [7] gives [7].
    • nums = [1, 2, 3, 4, 5, 6] gives [3, 1, 5, None, 2, 4, 6].
    • A list of 10,000 consecutive integers gives a tree of height 14.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free