Binary Search Tree
Sorted Array
Tree Conversion
Duplicate Question
Data Structures

Convert Sorted Array to Binary Search Tree

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Problem Description

The task of converting a sorted array into a binary search tree (BST) is a common problem in computer science, often encountered in algorithm-focused interviews. Specifically, the goal is to transform a sorted (in ascending order) integer array into a height-balanced BST, meaning the depths of the two subtrees of every node never differ by more than one.

Approach to the Solution

To convert a sorted array into a balanced BST, the most effective method involves using a recursive approach with the help of the divide-and-conquer technique, leveraging the properties of BSTs. The middle element of the array is chosen as the root to ensure the tree remains balanced. Let's break down the steps:

  1. Base Case and Recursive Division:
    • If the array is empty, return None.
    • Find the middle element of the array to keep the tree balanced.
    • Once the middle element is selected as the root, apply the same process to the left subarray for the left subtree and the right subarray for the right subtree.
  2. Class Definition:
    • Define a TreeNode class to create nodes where each node includes a value, a reference to the left child, and a reference to the right child.
  3. Recursive Function:
    • A function is defined that:
      • Calculates the middle index.
      • Recursively builds the tree by considering the subarrays to the left and right of this index.

Example

Consider the sorted array, nums = [-10, -3, 0, 5, 9].

To form a balanced BST:

  • Choose 0 as the root (middle of array).
  • For the left subtree, take the subarray [-10, -3], with -3 as its root.
  • For the right subtree, take [5, 9], with 9 as its root.
  • This results in a BST structure:
  • Single Element Array: Directly becomes the root.
  • Empty Array: Should return None.
  • Larger Arrays: The algorithm efficiently manages them through recursive partitioning, maintaining balance according to the BST properties.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.