AlgoFrames

Choose an insertion order for balance

Standard · Trace the algorithm · about 6 min

You will insert the keys 1 to 7 into an empty plain BST and want a tree of height 3. A safe rule is middle first: insert the middle key, then do the same for the keys left of it, then for the keys right of it.

Answer each question before the step plays.

Example 1

Input:

[[1,2,3,4,5,6,7]]

Output:

[4,2,1,3,6,5,7]

Inserting in this order gives the perfect tree of height 3.

Constraints

  • Middle of indices lo..hi is (lo + hi) / 2 rounded down
  • Left half before right half

Learn the idea first: Why balance matters, a visual lesson.

More Why balance matters problems