BALT-P5

B-tree insert

Practice 5 of 6Balanced trees8 tests

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

  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 keysNot run
3The fourth key splitsNot run
410 to 100Not run
5100 down to 1Not run
6Repeated keysNot run
72,000 mixed keysNot run
820,000 in orderNot run