BALT-P4

Red-black insert

Practice 4 of 6Balanced trees8 tests

The problem

Write the insert of a red-black tree (lesson 4). rb_insert(root, key) inserts the key into the tree whose root is root (None for an empty tree) and returns the new root. Each node has a field red: True for red, False for black. After every insert the tree must obey the four rules:

  1. Every node is red or black.
  2. The root is black.
  3. A red node never has a red child.
  4. Every path from a node down to a missing child passes the same number of black nodes.

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.

Different correct methods give different trees, so the tests do not check the exact shape. They check the four rules, that the keys are all there in order, and that the height is at most 2 log₂(n + 1). The left-leaning version from lesson 4 is accepted. All keys are different.

Limits

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

Builds on BALT-4 Red-black 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.

8 tests, not run yet
Test results
#TestResultReads · time
1One keyNot run
2Three in orderNot run
31 to 8Not run
48 down to 1Not run
5ZigzagNot run
6Same keys, colours keptNot run
71 to 1,000 in orderNot run
810,000 keysNot run