add method

void add(
  1. String word
)

Inserts word. A word already present (distance 0 to an existing node) is ignored, keeping the tree a set rather than a multiset.

Example:

final BkTree t = BkTree()..add('book')..add('books')..add('cake');
t.search('boo', 2); // ['book', 'books']

Audited: 2026-06-12 11:26 EDT

Implementation

void add(String word) {
  final _BkNode? root = _root;
  if (root == null) {
    _root = _BkNode(word);
    _size++;
    return;
  }
  _BkNode node = root;
  // Descend until we find a free distance slot; reuse the slot's child on
  // collision so equidistant words still get a home.
  while (true) {
    final int d = _distance(node.word, word);
    if (d == 0) return; // already present
    final _BkNode? child = node.children[d];
    if (child == null) {
      node.children[d] = _BkNode(word);
      _size++;
      return;
    }
    node = child;
  }
}