ExamAdda Logo

Convert Sorted Array to Binary Search Tree

Easy

Given an integer array nums where the elements are sorted in ascending order, convert it into a height-balanced Binary Search Tree (BST).

A height-balanced binary tree is a binary tree in which the difference between the heights of the left and right subtrees of every node is at most 1.

Return the root of the resulting Binary Search Tree.

Example 1

Input

n = 5
nums = [-10, -3, 0, 5, 9]

Output

0 -10 -3 5 9

Explanation

Choosing the middle element 0 as the root gives a balanced BST.

One valid tree is: 

        0
      / \
   -10   5
      \    \
      -3    9

The preorder traversal is:

0 -10 -3 5 9

Example 2

Input

n = 2
nums = [1, 3]

Output

1 3

Explanation

Either middle element can be selected when the array has an even number of elements. Choosing 1 as the root gives:

    1

     \

      3

 

This tree is height-balanced.

Constraints

1 <= nums.length <= 20
-10^4 <= nums[i] <= 10^4
nums is sorted in ascending order.
All elements of nums are unique.
The resulting BST must be height-balanced.

Hints:

Hint 1

Since the array is already sorted, the middle element is a good choice for the root.

Hint 2

Recursively build the left subtree from the left half and the right subtree from the right half.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 21, 2026

Last updated

Aug 22, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output