Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Need a decent red black tree implementation

Where can I find one ready for use? Or for that matter, a good collection of "standard" data structures, if you know of any?

like image 972
Hamster Avatar asked Nov 17 '10 12:11

Hamster


People also ask

How do you implement a red-black tree?

To implement the red-black tree, besides the child nodes left and right , we need a reference to the parent node and the node's color. We store the color in a boolean , defining red as false and black as true . We implement the red-black tree in the RedBlackTree class.

Why do we need RB tree?

Now, the question arises that why do we require a Red-Black tree if AVL is also a height-balanced tree. The Red-Black tree is used because the AVL tree requires many rotations when the tree is large, whereas the Red-Black tree requires a maximum of two rotations to balance the tree.

What are the invariants that needs to be maintained for a BST to be a red-black tree?

The bookkeeping invariant: all paths through the tree have the same number of black nodes. A relaxed balance invariant: there is at most one red node that has a red parent.

Is red-black tree important for interview?

Questions on red-black trees are very frequently asked in interview questions. Red-black trees are specialized binary search trees which are always balanced, and hence overcomes the short coming of binary search trees which can become unbalanced, resulting in degraded efficiency of search operations.


2 Answers

I wrote a red-black tree in javascript, available here: https://github.com/vadimg/js_bintrees or as bintrees in npm. Unlike the other implementations, it has unit tests.

like image 169
vadimg Avatar answered Sep 21 '22 15:09

vadimg


This library has red-black trees

like image 20
Thomas Avatar answered Sep 24 '22 15:09

Thomas