0
0
DSA C++programming

Convert Sorted Array to Balanced BST in DSA C++

Choose your learning style9 modes available
Mental Model
We pick the middle element of the sorted array as the root to keep the tree balanced. Then we do the same for left and right parts to build left and right subtrees.
Analogy: Imagine you have a sorted list of books on a shelf. To organize them into a balanced pyramid stack, you pick the middle book as the base center, then build left and right stacks from the halves, so the pyramid stays even on both sides.
Sorted array: [1, 2, 3, 4, 5, 6, 7]
Balanced BST:
      4
     / \
    2   6
   / \ / \
  1  3 5  7
Dry Run Walkthrough
Input: sorted array: [1, 2, 3, 4, 5, 6, 7]
Goal: Build a balanced binary search tree (BST) from the sorted array
Step 1: Pick middle element 4 as root
4 ↑ (root)
Left array: [1, 2, 3]
Right array: [5, 6, 7]
Why: Middle element keeps tree balanced by splitting array evenly
Step 2: Build left subtree from [1, 2, 3], pick 2 as left child
    4
   / 
  2 ↑
Left array: [1]
Right array: [3]
Why: Repeat middle element selection for left subtree
Step 3: Build left child of 2 from [1], pick 1
    4
   / 
  2
 / 
1 ↑
Why: Single element becomes leaf node
Step 4: Build right child of 2 from [3], pick 3
    4
   / 
  2
 / \
1   3 ↑
Why: Single element becomes leaf node
Step 5: Build right subtree from [5, 6, 7], pick 6 as right child
    4
   / \
  2   6 ↑
 / \ 
1   3
Right array left: [5]
Right array right: [7]
Why: Repeat middle element selection for right subtree
Step 6: Build left child of 6 from [5], pick 5
    4
   / \
  2   6
 / \ / 
1  3 5 ↑
Why: Single element becomes leaf node
Step 7: Build right child of 6 from [7], pick 7
    4
   / \
  2   6
 / \ / \
1  3 5  7 ↑
Why: Single element becomes leaf node
Result:
Balanced BST:
      4
     / \
    2   6
   / \ / \
  1  3 5  7
Annotated Code
DSA C++
#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

TreeNode* sortedArrayToBSTHelper(const vector<int>& nums, int left, int right) {
    if (left > right) return nullptr; // base case: no elements

    int mid = left + (right - left) / 2; // find middle index
    TreeNode* root = new TreeNode(nums[mid]); // create root node with middle element

    root->left = sortedArrayToBSTHelper(nums, left, mid - 1); // build left subtree
    root->right = sortedArrayToBSTHelper(nums, mid + 1, right); // build right subtree

    return root; // return root of this subtree
}

TreeNode* sortedArrayToBST(const vector<int>& nums) {
    return sortedArrayToBSTHelper(nums, 0, (int)nums.size() - 1);
}

void printInOrder(TreeNode* root) {
    if (!root) return;
    printInOrder(root->left);
    cout << root->val << " ";
    printInOrder(root->right);
}

int main() {
    vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
    TreeNode* root = sortedArrayToBST(nums);
    printInOrder(root);
    cout << "\n";
    return 0;
}
if (left > right) return nullptr; // base case: no elements
stop recursion when no elements left to process
int mid = left + (right - left) / 2; // find middle index
choose middle element to keep tree balanced
TreeNode* root = new TreeNode(nums[mid]); // create root node with middle element
create node with middle value
root->left = sortedArrayToBSTHelper(nums, left, mid - 1); // build left subtree
recursively build left subtree from left half
root->right = sortedArrayToBSTHelper(nums, mid + 1, right); // build right subtree
recursively build right subtree from right half
return root; // return root of this subtree
return constructed subtree root
OutputSuccess
1 2 3 4 5 6 7
Complexity Analysis
Time: O(n) because each element is visited once to create a node
Space: O(log n) due to recursion stack depth for balanced tree
vs Alternative: Compared to inserting elements one by one into BST (O(n log n)), this method builds balanced BST in linear time
Edge Cases
empty array
returns nullptr, no tree created
DSA C++
if (left > right) return nullptr; // base case: no elements
array with one element
creates single node tree
DSA C++
if (left > right) return nullptr; // base case: no elements
array with two elements
middle picks first element, second becomes right child
DSA C++
int mid = left + (right - left) / 2; // find middle index
When to Use This Pattern
When you see a sorted array and need a balanced BST, use the middle element as root and recursively build subtrees from halves to keep balance.
Common Mistakes
Mistake: Picking first or last element as root instead of middle
Fix: Always pick middle element to keep tree balanced
Mistake: Not handling base case when left > right causing infinite recursion
Fix: Add base case to return nullptr when no elements remain
Summary
Builds a balanced binary search tree from a sorted array by recursively choosing middle elements as roots.
Use when you want a height-balanced BST from sorted data for efficient search.
The key is picking the middle element to keep left and right subtrees balanced.