An implementation of the treap data structure for node.js and the browser

An implementation of the treap data structure for node.js and the browser

Treaps are self-balancing binary trees
which combine the properties of heaps and binary search trees. Each node has a
*key*, which follows binary search tree ordering, and a *priority*, which
follows heap ordering. Treaps can be used to efficiently implement sets and
sorted lists, among other things.

`var treap = ;var t = treap; // Insert some keys, augmented with data fields t;t;t; // Look up treap elements var a = t;var b = t; console; // 5 { foo: 12 } console; // 2 { foo: 8 } // Remove treap elements t; // by reference to node t; // by key `

Factory method to initialize a new, empty treap.

Merges the two treaps into a single treap, given that `maxKey(lTreap)`

< `minKey(rTreap)`

.

Inserts a node with the given `key`

(optionally augmented with an arbitrary `data`

object).

Returns the node with the given key, or null if no such node exists. The node object contains `key`

and `data`

fields, as wells as fields for navigating the search tree: `left`

, `right`

,
and `parent`

.

Remove the node with the given numeric `key`

, or the given `node`

itself.

Returns a list containing all nodes with `from`

<= `node.key`

<= `to`

.

Returns the node with the kth smallest key.

Splits the treap into two treaps `lTreap`

and `rTreap`

such that `maxKey(lTreap)`

< `k`

<= `minKey(rTreap)`

. The two new treaps are retured as the list ```
[lTreap,
rTreap]
```

.

Performs an inorder traversal of the tree and executes function `fn`

for each node. `fn`

is passed the arguments `(node, i)`

, where `i`

counts the callings of `fn`

.
The traversal can be aborted before it finishes by `fn`

returning true.

Returns the root node.

Returns the number of nodes in the treap.

Tests are written with Mocha and can be run with `npm test`

.

(The MIT License)

Copyright (c) 2012 Brenden Kokoszka

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.