BALT-P3

AVL insert

Practice 3 of 6Balanced trees9 tests

The problem

Write the insert of an AVL tree (lesson 3). avl_insert(root, key) inserts the key into the tree whose root is root (None for an empty tree) and returns the new root. After every insert, every node must obey the AVL rule: its two subtrees differ in height by at most 1.

root = None
for key in [1, 2, 3]:
    root = avl_insert(root, key)
# root is 2, with children 1 and 3

The tests start from an empty tree (None), insert the keys one at a time with root = f(root, key), and then read your tree through .value, .left and .right. Keep those field names.

An AVL insert is fully determined by the keys and their order, so the tests check the exact shape of small trees, and the height and balance of big ones. All keys are different.

Limits

  • Up to 10,000 inserts; each one should take O(log n) time.

Builds on BALT-2 Rotations and BALT-3 AVL trees.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1Three in orderNot run
2Left-leftNot run
3Left-rightNot run
4Right-leftNot run
5The lesson's double rotationNot run
61 to 7Not run
7Mixed order, 20 keysNot run
81 to 1,000 in orderNot run
910,000 keysNot run