Search⌘ K
AI Features

Convert Sorted Array to Binary Search Tree

Explore how to construct a height-balanced binary search tree from a sorted integer array. Understand the height-balanced property and practice implementing solutions in a hands-on coding environment to enhance your problem-solving skills in tree-based interview questions.

Statement

Given an array of integers, nums, sorted in ascending order, your task is to construct a height-balanced binary search tree (BST) from this array.

In a height-balanced BST, the difference of heights of the left subtree and right subtree of any node is not more than 1.

Note: There can be multiple valid BSTs for a given input.

Constraints:

  • 11 \leq nums.length 103\leq 10^3
  • 104-10^4 \leq nums[i] 104\leq 10^4
  • nums is sorted in strictly ascending order.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Convert Sorted Array to a Binary Search Tree

1.

Select all valid BSTs that can be created with the given sorted array:

[5, 10, 15, 20] Multi-select

A.
  5
 / \
15  10
     \
      20
B.
  10
 /  \
5    15
      \
       20
C.
    15
   /  \
  5    20
 /   
10
D.
    15
   /  \
  10   20
 /
5

1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in the following coding playground.

Python
usercode > main.py
# Definition of a binary tree node
#
# class TreeNode:
# def __init__(self, data):
# self.data = data
# self.left = None
# self.right = None
from ds_v1.BinaryTree.BinaryTree import TreeNode
def sorted_array_to_bst(nums):
# Replace this placeholder return statement with your code
return []
Convert Sorted Array to Binary Search Tree