TheAlgorithms/Go · critical
Must be >= 3 keys
Error message
Must be >= 3 keys
What it means
NewBTree panics when maxKeys <= 2 because a B-tree with fewer than 3 max keys cannot satisfy the minimum-key invariants of internal nodes (minKeys = (maxKeys-1)/2 leaves no room to split or borrow). The library rejects structurally impossible tree parameters at construction time.
Source
Thrown at structure/tree/btree.go:37
func minKeys(maxKeys int) int {
return (maxKeys - 1) / 2
}
func NewBTreeNode[T constraints.Ordered](maxKeys int, isLeaf bool) *BTreeNode[T] {
if maxKeys <= 0 {
panic("BTree maxKeys cannot be zero")
}
return &BTreeNode[T]{
keys: make([]T, maxKeys),
children: make([]*BTreeNode[T], maxKeys+1),
isLeaf: isLeaf,
}
}
func NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] {
if maxKeys <= 2 {
panic("Must be >= 3 keys")
}
return &BTree[T]{
root: nil,
maxKeys: maxKeys,
}
}
func (node *BTreeNode[T]) Verify(tree *BTree[T]) {
minKeys := minKeys(tree.maxKeys)
if node != tree.root && node.numKeys < minKeys {
panic("node has too few keys")
} else if node.numKeys > tree.maxKeys {
panic("node has too many keys")
}
}
func (node *BTreeNode[T]) IsFull(maxKeys int) bool {
return node.numKeys == maxKeysView on GitHub (pinned to 5ba447ec5f)
Solutions
- Call NewBTree with maxKeys >= 3 (4 is a common even choice).
- Clamp or validate configuration values before constructing the tree.
- If you need a smaller branching factor, B-trees are not the right structure; use a BST/2-3 tree implementation.
Example fix
// before tree := NewBTree[int](2) // after tree := NewBTree[int](4)
Defensive patterns
Strategy: validation
Validate before calling
func NewBTreeSafe[T constraints.Ordered](maxKeys int) *BTree[T] {
if maxKeys < 3 { maxKeys = 4 }
return NewBTree[T](maxKeys)
} Try / catch
defer func() {
if r := recover(); r != nil {
log.Fatalf("invalid BTree maxKeys: %v", r)
}
}() Prevention
- Always pass a literal >= 3 or clamp config input
- Default to 4 if the setting is missing
- Remember the parameter is maxKeys, not tree order
When it happens
Trigger: Calling NewBTree with 0, 1, or 2, e.g. NewBTree[int](2), often from a misconfigured degree setting or a default zero value of an int variable.
Common situations: Zero-valued struct field used as maxKeys; misunderstanding whether the parameter is 'order' vs 'max keys'; hardcoded small values in tests.
Related errors
- BTree maxKeys cannot be zero
- node has too few keys
- node has too many keys
- Called InsertNonFull() with a full node
- deleting out of bounds key
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/9083257767f06227.
Report an issue: GitHub.