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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Three in order | Not run | |
| 2 | Left-left | Not run | |
| 3 | Left-right | Not run | |
| 4 | Right-left | Not run | |
| 5 | The lesson's double rotation | Not run | |
| 6 | 1 to 7 | Not run | |
| 7 | Mixed order, 20 keys | Not run | |
| 8 | 1 to 1,000 in order | Not run | |
| 9 | 10,000 keys | Not run |