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:
- Every node is red or black.
- The root is black.
- A red node never has a red child.
- 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
- 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 | One key | Not run | |
| 2 | Three in order | Not run | |
| 3 | 1 to 8 | Not run | |
| 4 | 8 down to 1 | Not run | |
| 5 | Zigzag | Not run | |
| 6 | Same keys, colours kept | Not run | |
| 7 | 1 to 1,000 in order | Not run | |
| 8 | 10,000 keys | Not run |