Trees and binary search trees · Exercise 34 of 100

Build a balanced BST from an array

Start with an array of distinct values sorted from smallest to largest and choose a middle value as the root. Build its left subtree from the smaller values and its right subtree from the larger values. Choosing a middle value at each split keeps the subtree sizes within one of each other and gives a height-balanced binary search tree.

Try it yourself

Build a tree from [2, 5, 9, 14, 20, 27, 35, 44]. Whenever a slice has two middle values, choose the lower one. What value becomes the right child of the root?

One-step hint

Underline the lower middle key of the full array. Cover that key and everything to its left, then apply the middle rule to the visible keys.

Worked solution
  1. The two middle values of the full array are 14 and 20. Choose 14 as the root, leaving [20, 27, 35, 44] for its right subtree.
  2. The middle values of that slice are 27 and 35. Choosing 27 makes it the root of the right subtree and thus the right child of 14.
DSA compiler