An implementation of a ternary search tree.

npm install tritium
2 downloads in the last week
8 downloads in the last month


A Javascript implementation of a ternary search tree.


> tritium = require('tritium');
> tree = tritium.ternarySearchTree();
> tree.add('airplane');
> tree.add('airport');
> tree.add('airside');
> tree.add('apple');
> tree.has('air');
> tree.has('apple');
> tree.has('apples');
> tree.prefixSearch('airp');
[ 'airplane', 'airport' ]
> tree.prefixSearch('air');
[ 'airplane',
  'airside' ]
> tree.prefixSearch('be')




Creates an empty ternary search tree.

Ternary search tree methods


Returns the root node of the tree.


Returns the number of words added to the tree. This is the same as the number of times add() has been called.


Returns the number of nodes in the tree.


Adds a new word to the tree.


Tests whether a given prefix is in the tree.

.prefixSearch(prefix [, limit])

Returns an array of words that begin with prefix. If limit is specified, the first limit words found during the traversal will be returned. For example:

> tree.add('timber');
> tree.add('tin');
> tree.prefixSearch('ti', 1);

At the moment, "timber" is found because the search is done in a depth-first manner. I plan to implement a breadth-first search in the future.

.traverse(visit [, data])

Performs a depth-first traversal of the tree, calling visit on each node. It optionally accepts an object that can store arbitrary information.

visit is a callback that has the same signature as traverse:

> tree.add('bar')
> tree.add('baz')
> d = { seen: [] };
> tree.traverse(function(node, data) {
... data.seen.push(node.character);
... return data;
... }, d);
> d
{ seen: [ 'b', 'a', 'r', 'z' ] }


I'm still working on the API but here are some tasks that need to be done:

  • Implement a breadth-first traversal and search
  • Add some benchmarks (how does it compare to other solutions?)
  • Implement a trie and compare performance

Stay tuned.

npm loves you