Tensorum
LeetCode 108 · BST

Convert Sorted Array to Binary Search Tree

LeetCode 108 · Easy · solution, intuition & step-by-step walkthrough

Root = middle element; recurse on halves.

EasyArrayDivide and ConquerTreeBinary Search TreeBinary Tree
64 msruntime · beats 4%
52.6 MBmemory · beats 100%
1approach
5accepted runs · last 28 Jun 2024

This is how I solved Convert Sorted Array to Binary Search Tree (LeetCode 108), an easy problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

The middle element of a sorted array is a perfect root: half the values go left, half go right. Recurse on each half and the tree stays height-balanced.

Approach

  1. 1

    traverse(start, end): empty range → None.

  2. 2

    mid = (start + end) // 2 becomes the node.

  3. 3

    Left subtree from [start, mid−1], right from [mid+1, end].

How I solved it

Divide by the middlePythonO(n) time
class Solution:
    def sortedArrayToBST(self, nums):
        def traverse(inorder, inStart, inEnd):
            if inStart > inEnd:
                return None
            mid = (inStart + inEnd) // 2
            root = TreeNode(inorder[mid])
            root.left = traverse(inorder, inStart, mid - 1)
            root.right = traverse(inorder, mid + 1, inEnd)
            return root
        return traverse(nums, 0, len(nums) - 1)
Loading the step-through…

Convert Sorted Array to Binary Search Tree — FAQ

What is the intuition behind Convert Sorted Array to Binary Search Tree?

The middle element of a sorted array is a perfect root: half the values go left, half go right. Recurse on each half and the tree stays height-balanced.

How do you solve Convert Sorted Array to Binary Search Tree (LeetCode 108)?

1. traverse(start, end): empty range → None. 2. mid = (start + end) // 2 becomes the node. 3. Left subtree from [start, mid−1], right from [mid+1, end].

What is the time and space complexity of Convert Sorted Array to Binary Search Tree?

Time: O(n). Space: O(log n) recursion. (Accepted approach: Divide by the middle.)

What are common mistakes in Convert Sorted Array to Binary Search Tree?

Either middle works for even lengths; the tests accept any balanced BST.