0
0
DSA Javascriptprogramming

Convert Sorted Array to Balanced BST in DSA Javascript

Choose your learning style9 modes available
Mental Model
We build a tree by picking the middle element as root to keep it balanced. Then we do the same for left and right parts.
Analogy: Imagine dividing a sorted list of books into three piles: the middle book goes on top, left pile forms the left stack, right pile forms the right stack, so the stacks stay balanced.
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 from the sorted array
Step 1: Pick middle element 4 as root
4
Array split: left=[1,2,3], right=[5,6,7]
Why: Middle element keeps tree balanced by dividing array evenly
Step 2: Build left subtree from [1,2,3], pick middle 2 as left child
    4
   / 
  2
Array split left=[1], right=[3]
Why: Recursively pick middle to keep left subtree balanced
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 middle 6 as right child
    4
   / \
  2   6
 / \
Why: Recursively pick middle to keep right subtree balanced
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 Javascript
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

function sortedArrayToBST(nums) {
  if (nums.length === 0) return null; // base case: empty array

  const mid = Math.floor(nums.length / 2); // find middle index
  const root = new TreeNode(nums[mid]); // middle element becomes root

  root.left = sortedArrayToBST(nums.slice(0, mid)); // build left subtree
  root.right = sortedArrayToBST(nums.slice(mid + 1)); // build right subtree

  return root;
}

function printBST(root) {
  if (!root) return "null";
  const left = printBST(root.left);
  const right = printBST(root.right);
  return `${root.val} -> (${left}, ${right})`;
}

// Driver code
const nums = [1, 2, 3, 4, 5, 6, 7];
const bstRoot = sortedArrayToBST(nums);
console.log(printBST(bstRoot));
if (nums.length === 0) return null; // base case: empty array
stop recursion when no elements left
const mid = Math.floor(nums.length / 2); // find middle index
choose middle element to keep tree balanced
const root = new TreeNode(nums[mid]); // middle element becomes root
create node for middle element
root.left = sortedArrayToBST(nums.slice(0, mid)); // build left subtree
recursively build left subtree from left half
root.right = sortedArrayToBST(nums.slice(mid + 1)); // build right subtree
recursively build right subtree from right half
OutputSuccess
4 -> (2 -> (1 -> (null, null), 3 -> (null, null)), 6 -> (5 -> (null, null), 7 -> (null, null)))
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: Naive approach inserting elements one by one into BST is O(n log n), this method is faster and produces balanced tree
Edge Cases
empty array
returns null, no tree created
DSA Javascript
if (nums.length === 0) return null; // base case: empty array
array with one element
creates single node tree
DSA Javascript
if (nums.length === 0) return null; // base case: empty array
array with two elements
root is first middle, left or right subtree has one node
DSA Javascript
const mid = Math.floor(nums.length / 2); // find middle index
When to Use This Pattern
When you see a sorted array and need a balanced search tree, use the middle element as root and build subtrees recursively 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 slicing array correctly for left and right subtrees
Fix: Use nums.slice(0, mid) for left and nums.slice(mid+1) for right
Summary
Builds a balanced binary search tree from a sorted array by choosing middle elements as roots.
Use when you want a height-balanced BST from sorted data for efficient search.
The key insight is picking the middle element splits the array evenly, keeping the tree balanced.