AlgoTales · Roadmap

Balanced BST

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A balanced search tree keeps its left and right sides about equally deep, so no path from the top is much longer than any other. Without balance, a tree built from sorted data leans like a chain, and its fast lookups turn into slow ones.

Practical use cases

  • Web app: Phone directory built from sorted data. A contacts feature loads names already sorted A to Z and inserts them one after another into a plain search tree. Every name goes to the right, so the tree becomes a long stick and each lookup checks almost every name. Building the tree from the middle name outward instead keeps it shallow, and a search over 100,000 contacts takes about 17 steps again.
  • Web app: Leaderboard that slows down over time. A game site inserts scores that mostly arrive in rising order, and after a week the leaderboard page crawls. The tree has leaned to one side, so lookups go through thousands of nodes. Switching to a self-balancing structure keeps the page fast however the scores arrive.
  • System: Ordered maps, indexes and operating systems. Ordered maps in many languages, database indexes and parts of operating systems use trees that rebalance themselves after changes. The promise is that even in the worst case, the tree never grows much deeper than the ideal, so every operation stays quick and predictable.

The story: The Leaning Phone Directory

Mira's school built a phone directory as a BST. The clerk typed in new students' roll numbers in the order they joined: 1, 2, 3, 4, 5, 6, 7. Every new number was bigger than the last, so every one went to the right. The tree grew like a long, leaning ladder.

On the exam day the clerk needed roll number 7. He had to step through 1, 2, 3, 4, 5, 6, 7: every single entry. "A BST is supposed to be fast!" he grumbled. Mrs. Sharma looked at the leaning ladder and smiled. "The rule is fine. The shape is the problem."

She sorted the numbers and rebuilt the tree: the middle number, 4, became the top. Then the middle of the left half (2) and the middle of the right half (6), and so on. Now the tree was short and wide, and roll number 7 took only three steps. A tree whose two sides stay about equally tall is called balanced. The same trick also builds a balanced BST from any sorted array.

How to spot this problem, and where you need it

A search tree that was fast in testing becomes slow in production because real data arrived in order and the tree turned into a long chain.

Signs you need it

  • Lookups were fast with random test data but crawl when data is imported sorted by id, date or name.
  • Drawing the tree shows a long diagonal line instead of a wide triangle, so depth is close to the number of items.
  • The task says "convert a sorted array to a balanced BST", or "height must differ by at most one".

Where to use it in a project

  • Bulk imports that build an ordered structure from already sorted CSV or database rows.
  • Choosing an ordered map or index that rebalances itself instead of a hand-written plain tree.

The solution

If you already have sorted data, pick the middle item as the top node, then build the left half into the left side and the right half into the right side, repeating the same rule. If data keeps arriving, use a self-balancing tree, which rotates a few nodes after an insert or delete to keep both sides about equal in depth.

Payoff: Before: 100,000 steps to find the last contact in a leaning tree. After: about 17 steps, however the data was ordered on arrival.

Explain it like I am 8

Stack of books vs a pyramid: if you pile 7 books in one tower, the top is far away; if you arrange them as a pyramid, every book is close to the top. A balanced tree is the pyramid. Picking the middle each time makes it.

How it works, step by step

  1. A BST's speed depends on its height. Keys inserted in sorted order produce a very tall stick.
  2. To build a balanced BST from a sorted list: pick the middle element as the root.
  3. Build the left subtree from the left half and the right subtree from the right half, using the same rule.
  4. For trees that keep changing, use a self-balancing tree (AVL or red-black), which rotates nodes after inserts and deletes to keep the height small.

The code in four languages

PHP

<?php
class Node {
    public ?Node $left = null;
    public ?Node $right = null;
    public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
    if ($n === null) return new Node($v);
    if ($v < $n->val) $n->left = insert($n->left, $v);
    else $n->right = insert($n->right, $v);
    return $n;
}

// Sorted list -> balanced BST: the middle becomes the root, repeat on each half
function sortedToBst(array $a, int $lo, int $hi): ?Node {
    if ($lo > $hi) return null;
    $mid = intdiv($lo + $hi, 2);
    $node = new Node($a[$mid]);
    $node->left = sortedToBst($a, $lo, $mid - 1);
    $node->right = sortedToBst($a, $mid + 1, $hi);
    return $node;
}

function height(?Node $n): int {                      // number of levels
    if ($n === null) return 0;
    return 1 + max(height($n->left), height($n->right));
}

$nums = [1, 2, 3, 4, 5, 6, 7];

$stick = null;
foreach ($nums as $v) $stick = insert($stick, $v);    // sorted inserts -> a stick
$balanced = sortedToBst($nums, 0, count($nums) - 1);

echo 'stick height:    ', height($stick), PHP_EOL;     // 7
echo 'balanced height: ', height($balanced), PHP_EOL;  // 3
echo 'balanced root:   ', $balanced->val, PHP_EOL;     // 4

JavaScript

class Node {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
  if (n === null) return new Node(v);
  if (v < n.val) n.left = insert(n.left, v);
  else n.right = insert(n.right, v);
  return n;
}

// Sorted list -> balanced BST: the middle becomes the root, repeat on each half
function sortedToBst(a, lo, hi) {
  if (lo > hi) return null;
  const mid = Math.floor((lo + hi) / 2);
  const node = new Node(a[mid]);
  node.left = sortedToBst(a, lo, mid - 1);
  node.right = sortedToBst(a, mid + 1, hi);
  return node;
}

function height(n) {                                  // number of levels
  if (n === null) return 0;
  return 1 + Math.max(height(n.left), height(n.right));
}

const nums = [1, 2, 3, 4, 5, 6, 7];

let stick = null;
for (const v of nums) stick = insert(stick, v);       // sorted inserts -> a stick
const balanced = sortedToBst(nums, 0, nums.length - 1);

console.log('stick height:    ' + height(stick));     // 7
console.log('balanced height: ' + height(balanced));  // 3
console.log('balanced root:   ' + balanced.val);      // 4

Java

public class Main {
    static class Node {
        int val;
        Node left, right;
        Node(int val) { this.val = val; }
    }

    static Node insert(Node n, int v) {
        if (n == null) return new Node(v);
        if (v < n.val) n.left = insert(n.left, v);
        else n.right = insert(n.right, v);
        return n;
    }

    // Sorted array -> balanced BST: the middle becomes the root, repeat on each half
    static Node sortedToBst(int[] a, int lo, int hi) {
        if (lo > hi) return null;
        int mid = (lo + hi) / 2;
        Node node = new Node(a[mid]);
        node.left = sortedToBst(a, lo, mid - 1);
        node.right = sortedToBst(a, mid + 1, hi);
        return node;
    }

    static int height(Node n) {                           // number of levels
        if (n == null) return 0;
        return 1 + Math.max(height(n.left), height(n.right));
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};

        Node stick = null;
        for (int v : nums) stick = insert(stick, v);      // sorted inserts -> a stick
        Node balanced = sortedToBst(nums, 0, nums.length - 1);

        System.out.println("stick height:    " + height(stick));     // 7
        System.out.println("balanced height: " + height(balanced));  // 3
        System.out.println("balanced root:   " + balanced.val);      // 4
    }
}

Go

package main

import "fmt"

type Node struct {
	val         int
	left, right *Node
}

func insert(n *Node, v int) *Node {
	if n == nil {
		return &Node{val: v}
	}
	if v < n.val {
		n.left = insert(n.left, v)
	} else {
		n.right = insert(n.right, v)
	}
	return n
}

// sortedToBst turns a sorted slice into a balanced BST: the middle becomes
// the root, repeat on each half.
func sortedToBst(a []int, lo, hi int) *Node {
	if lo > hi {
		return nil
	}
	mid := (lo + hi) / 2
	node := &Node{val: a[mid]}
	node.left = sortedToBst(a, lo, mid-1)
	node.right = sortedToBst(a, mid+1, hi)
	return node
}

func height(n *Node) int { // number of levels
	if n == nil {
		return 0
	}
	return 1 + max(height(n.left), height(n.right))
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6, 7}

	var stick *Node
	for _, v := range nums {
		stick = insert(stick, v) // sorted inserts -> a stick
	}
	balanced := sortedToBst(nums, 0, len(nums)-1)

	fmt.Println("stick height:   ", height(stick))    // 7
	fmt.Println("balanced height:", height(balanced)) // 3
	fmt.Println("balanced root:  ", balanced.val)     // 4
}

Time: O(n) · Extra space: O(log n). Building from a sorted list touches each element once, and the recursion is only as deep as the balanced tree (about log n levels).

Watch out for

  • Inserting an already-sorted list one by one and expecting a fast tree. It becomes a stick.
  • Believing a balanced tree must be perfect. It only needs both sides of every node to be about the same height.
  • Rebuilding the whole tree after every insert. Self-balancing trees fix the shape with a few local rotations instead.

Quick check

  1. What tree do you get by inserting 1, 2, 3, 4, 5 in that order into a plain BST?
    • A balanced tree
    • A stick leaning right
    • A stick leaning left
  2. To balance a sorted list, which element becomes the root?
    • The first
    • The last
    • The middle
  3. Why do we care about balance?
    • Search, insert and delete cost depends on the height
    • It makes the keys sorted
    • It reduces the number of keys