Advanced topics · Exercise 94 of 100
Balanced BST from a sorted array
Given distinct keys in increasing order, use a middle key as the root of a binary search tree. Repeat on the smaller keys to build the left subtree and on the larger keys to build the right subtree. Splitting each slice near its middle keeps the two subtree heights within one level of each other.
Try it yourself
Build a tree from [2, 5, 9, 12, 16, 21, 30, 44]. Whenever a slice has two middle keys, choose the smaller one. What key becomes the root's right child?
One-step hint
Trim a key from each end until the middle pair remains. Circle the lower key, then repeat on all the original keys to its right.
Worked solution
- The whole array has middle keys 12 and 16, so 12 becomes the root. Its right subtree uses [16, 21, 30, 44].
- The middle keys of that slice are 21 and 30. Choosing the smaller gives 21 as the root's right child.