The problem
Write the insert of a B-tree in which every node holds 1 to 3 keys (lesson 5, with t = 2). A node is a BNode with a sorted list keys and a list kids of children, empty for a leaf. btree_insert(root, key) inserts the key into the tree whose root is root (None for an empty tree) and returns the root. If the key is already in the tree, change nothing.
After every insert the tree must obey the rules:
- every node holds 1 to 3 keys, in increasing order;
- a node with k keys that is not a leaf has k + 1 children, and the keys of each child lie between the keys on either side of it;
- all leaves are at the same depth.
root = None
for key in [10, 20, 30, 40]:
root = btree_insert(root, key)
# one possible answer: root.keys == [20],
# root.kids hold [10] and [30, 40]
Splitting on the way down (as in the lesson) and splitting on the way back up both give valid trees, so the tests check the rules, the keys and the height, not the exact shape.
Limits
- Up to 20,000 inserts; each one should take O(log n) time.
Builds on BALT-5 B-trees and disks.
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 keys | Not run | |
| 3 | The fourth key splits | Not run | |
| 4 | 10 to 100 | Not run | |
| 5 | 100 down to 1 | Not run | |
| 6 | Repeated keys | Not run | |
| 7 | 2,000 mixed keys | Not run | |
| 8 | 20,000 in order | Not run |