VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorted-array-to-balanced-bst/

⇱ Sorted Array to Balanced BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorted Array to Balanced BST

Last Updated : 30 Mar, 2026

Given a sorted array arr[]. Convert it into a Balanced Binary Search Tree (BST). Return the root of the BST.

A Balanced Binary Search Tree (BST) is a type of binary tree in which the difference between the heights of the left and right subtrees of every node is at most one.

Examples:

Input: arr[] = [10, 20, 30]
Output: [[20], [10, 30]]
Explanation: The above sorted array converted to below Balanced Binary Search Tree.

πŸ‘ 420046833

Input: arr[] = [1, 5, 9, 14, 23, 27]
Output: [[9], [1, 23], [N, 5, 14, 27]]
Explanation: The above sorted array converted to below Balanced Binary Search Tree.

πŸ‘ 7

[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space

The idea is to use recursion to build the tree from a sorted array. We first find the middle element of the array and make it the root of the tree.
Then we recursively repeat the same process for the left subarray (to form the left subtree) and the right subarray (to form the right subtree). 

Why the Middle Element?
Choosing the middle element ensures that:

  • Half of the elements lie on the left side (smaller values)
  • Half of the elements lie on the right side (larger values)

This keeps the number of nodes in both subtrees as equal as possible, ensuring the tree remains height-balanced.


Output
9 
1 23 
N 5 14 27 

[Expected Approach - 2] Using queue - O(n) Time and O(n) Space

The idea is to traverse the tree in level order manner, starting from root node. Check for each node, if left subtree exists, then create the left node and push it into queue. Similarly, if right subtree exists, then create the right node and push it into queue.

Step-by-step approach:

  • Initialize a queue with the root node (middle of array) and its range [0, n-1].
  • While the queue isn’t empty:
    Pop the front node with its [start, end] range.
    Find mid = (start + end) / 2.
    If start < mid, create the left child using the middle of [start, mid-1], link it, and push it with its range.
    If end > mid, create the right child using the middle of [mid+1, end], link it, and push it with its range.
  • Return the root.

Output
9 
1 23 
N 5 14 27 
Comment