Skip to lesson

Build a balanced BST

Constructing balanced trees from sorted sequences ensures minimal tree height and logarithmic search time.

Converting a sorted array into a balanced BST

To build a height-balanced binary search tree, the middle element should become the root. Choosing the median guarantees an equal number of elements on the left and right.

Example 1 · Brute force: insert the sorted values one by one (O(n²) time, height n)

SortedInsertDemo.javaJava
public class SortedInsertDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static TreeNode insert(TreeNode root, int val) {        if (root == null) return new TreeNode(val);        if (val < root.val) root.left = insert(root.left, val);        else root.right = insert(root.right, val);        return root;    }
    static int height(TreeNode root) {        if (root == null) return 0;        return 1 + Math.max(height(root.left), height(root.right));    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5, 6, 7};        TreeNode root = null;        for (int v : nums) {            root = insert(root, v);        }        System.out.println("Root value: " + root.val);        System.out.println("Tree height: " + height(root));    }}
Output
Root value: 1
Tree height: 7

What this code does

  • Each value is larger than every value before it, so it walks down the whole right chain before it is attached: 0 + 1 + 2 + ... steps, which is O(n²).
  • The result is a chain of height 7, not a balanced tree of height 3, so later searches cost O(n) too.

Example 2 · Optimal: take the middle as the root (O(n) time, O(log n) space)

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static TreeNode sortedArrayToBST(int[] nums) {        return build(nums, 0, nums.length - 1);    }
    static TreeNode build(int[] nums, int start, int end) {        if (start > end) return null;        int mid = start + (end - start) / 2;        TreeNode root = new TreeNode(nums[mid]);        root.left = build(nums, start, mid - 1);        root.right = build(nums, mid + 1, end);        return root;    }
    static int height(TreeNode root) {        if (root == null) return 0;        return 1 + Math.max(height(root.left), height(root.right));    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5, 6, 7};        TreeNode root = sortedArrayToBST(nums);        System.out.println("Root value: " + root.val);        System.out.println("Tree height: " + height(root));    }}
Output
Root value: 4
Tree height: 3

What this code does

  • Midpoint element creates the root node at each recursive step.
  • Left and right subarrays recursively build balanced child subtrees.
  • Seven elements produce a perfectly balanced tree of height three.
  • Why it is faster: the middle value becomes the root, so each value is placed exactly once without walking down from the top, and both sides stay equal in size.

A divide-and-conquer algorithm picks mid = (start + end) / 2 as the root. Recursively construct the left child from the left subarray range. Recursively construct the right child from the right subarray range. Trace sorted array [1, 2, 3, 4, 5, 6, 7]. The middle element is 4, which becomes the tree root. The left range [1, 2, 3] picks 2 as left child with children 1 and 3. The right range [5, 6, 7] picks 6 as right child with children 5 and 7. This produces a perfectly balanced tree of height 3 in O(n) linear time.

Converting a sorted linked list into a BST

Linked lists lack constant-time indexing, making finding the middle element slower. A naive approach uses fast and slow pointers to find the middle in O(n log n) time.

Example 3 · Sorted Linked List to BST in O(n) Time

Main.javaJava
public class Main {    static class ListNode {        int val;        ListNode next;        ListNode(int val) { this.val = val; }    }
    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static ListNode head;
    static TreeNode sortedListToBST(ListNode node) {        head = node;        int size = count(node);        return build(0, size - 1);    }
    static int count(ListNode node) {        int c = 0;        while (node != null) { c++; node = node.next; }        return c;    }
    static TreeNode build(int start, int end) {        if (start > end) return null;        int mid = start + (end - start) / 2;        TreeNode leftChild = build(start, mid - 1);
        TreeNode root = new TreeNode(head.val);        root.left = leftChild;        head = head.next;
        root.right = build(mid + 1, end);        return root;    }
    public static void main(String[] args) {        ListNode list = new ListNode(1);        list.next = new ListNode(2);        list.next.next = new ListNode(3);
        TreeNode root = sortedListToBST(list);        System.out.println("Root: " + root.val + ", Left: " + root.left.val + ", Right: " + root.right.val);    }}
Output
Root: 2, Left: 1, Right: 3

What this code does

  • Traverse list length once to establish index boundaries.
  • Left subtree builds first, positioning head exactly at the root value.
  • The list pointer advances sequentially, achieving O(n) total time.

An optimal linear-time algorithm simulates an inorder traversal directly. Count the total list length first. Recursively build the left subtree of size n / 2. Then consume the current linked list head to instantiate the root node. Advance the linked list pointer to the next element. Finally recursively build the right subtree from remaining list nodes in O(n) total time.

Rebalancing an existing skewed BST

Over time, arbitrary insertions and deletions can cause a BST to become skewed. We can rebalance any unbalanced BST without complex rotation algorithms.

Example 4 · Rebalancing a Skewed BST

Main.javaJava
import java.util.ArrayList;import java.util.List;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static void inorder(TreeNode node, List<Integer> list) {        if (node == null) return;        inorder(node.left, list);        list.add(node.val);        inorder(node.right, list);    }
    static TreeNode buildFromList(List<Integer> list, int start, int end) {        if (start > end) return null;        int mid = start + (end - start) / 2;        TreeNode root = new TreeNode(list.get(mid));        root.left = buildFromList(list, start, mid - 1);        root.right = buildFromList(list, mid + 1, end);        return root;    }
    static TreeNode balanceBST(TreeNode root) {        List<Integer> list = new ArrayList<>();        inorder(root, list);        return buildFromList(list, 0, list.size() - 1);    }
    static int height(TreeNode root) {        if (root == null) return 0;        return 1 + Math.max(height(root.left), height(root.right));    }
    public static void main(String[] args) {        TreeNode skewed = new TreeNode(1);        skewed.right = new TreeNode(2);        skewed.right.right = new TreeNode(3);        skewed.right.right.right = new TreeNode(4);
        System.out.println("Skewed height: " + height(skewed));        TreeNode balanced = balanceBST(skewed);        System.out.println("Balanced height: " + height(balanced));    }}
Output
Skewed height: 4
Balanced height: 3

What this code does

  • Inorder traversal extracts all keys into sorted list form.
  • Divide and conquer rebuilds a height-balanced binary search tree.
  • Height drops from 4 down to 3 in O(n) total running time.

First, perform an inorder traversal to collect all node values into a sorted list. Second, apply the sorted array divide-and-conquer construction algorithm on that list. Because inorder traversal takes O(n) time and balanced construction takes O(n) time, total rebalancing is O(n). This simple technique restores minimal height in linear time.

Next step

Check your understanding

10 quick questions