Red-Black Tree Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Red-Black Tree runs in O(log n) time and O(n) space, in JavaScript as in every other language.
- ✓None. Map is a hash table that iterates in insertion order, and there is no ordered collection in the language.
- ✓If you do implement one, prefer explicit null children with checks over the shared sentinel design that classic C implementations use, because the sentinel is a single object and JavaScript gives you no way to make it read-only cheaply enough to be safe.
- ✓The JavaScript trap: The classic textbook implementation uses one shared NIL node, always black, as the child of every leaf, which removes a great many null checks from the fix-up code.
- ✓Node objects are individually allocated and pointer-chased, the worst case for the cache. Assign every field in the constructor so V8 keeps one hidden class across all nodes and the property loads stay monomorphic.
What Red-Black Tree actually is
Red-Black Tree in JavaScript: what you actually reach for
JavaScript implementation
const RED = 'red';
const BLACK = 'black';
class RbNode {
constructor(key, value) {
// Every field assigned here: one hidden class for all nodes.
this.key = key;
this.value = value;
this.color = RED; // new nodes are red; fix-up restores invariants
this.left = null;
this.right = null;
this.parent = null;
}
}
class RedBlackTree {
constructor(cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
this.root = null;
this.cmp = cmp;
}
// Explicit null children, NOT a shared sentinel. The classic C design
// uses one shared NIL node to remove null checks from the fix-up; a
// faithful transcription then writes to it during the delete fix-up,
// and because every leaf is the SAME object that single assignment
// corrupts the whole tree at once. The symptom shows up much later,
// in a traversal, far from the line that caused it.
#isRed(node) {
return node !== null && node.color === RED;
}
#rotateLeft(x) {
const y = x.right;
x.right = y.left;
if (y.left !== null) y.left.parent = x;
y.parent = x.parent;
if (x.parent === null) this.root = y;
else if (x === x.parent.left) x.parent.left = y;
else x.parent.right = y;
y.left = x;
x.parent = y;
}
#rotateRight(x) {
const y = x.left;
x.left = y.right;
if (y.right !== null) y.right.parent = x;
y.parent = x.parent;
if (x.parent === null) this.root = y;
else if (x === x.parent.right) x.parent.right = y;
else x.parent.left = y;
y.right = x;
x.parent = y;
}
insert(key, value) {
let parent = null;
let node = this.root;
while (node !== null) {
parent = node;
const c = this.cmp(key, node.key);
if (c === 0) { node.value = value; return; }
node = c < 0 ? node.left : node.right;
}
const fresh = new RbNode(key, value);
fresh.parent = parent;
if (parent === null) this.root = fresh;
else if (this.cmp(key, parent.key) < 0) parent.left = fresh;
else parent.right = fresh;
this.#fixInsert(fresh);
}
#fixInsert(z) {
while (this.#isRed(z.parent)) {
const gp = z.parent.parent;
if (gp === null) break;
if (z.parent === gp.left) {
const uncle = gp.right;
if (this.#isRed(uncle)) {
z.parent.color = BLACK; uncle.color = BLACK; gp.color = RED; z = gp;
} else {
if (z === z.parent.right) { z = z.parent; this.#rotateLeft(z); }
z.parent.color = BLACK; gp.color = RED; this.#rotateRight(gp);
}
} else {
const uncle = gp.left;
if (this.#isRed(uncle)) {
z.parent.color = BLACK; uncle.color = BLACK; gp.color = RED; z = gp;
} else {
if (z === z.parent.left) { z = z.parent; this.#rotateRight(z); }
z.parent.color = BLACK; gp.color = RED; this.#rotateLeft(gp);
}
}
}
this.root.color = BLACK; // invariant 1: the root is always black
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Red-Black Tree?
None. Map is a hash table that iterates in insertion order, and there is no ordered collection in the language.
What is the most common JavaScript mistake when implementing Red-Black Tree?
The classic textbook implementation uses one shared NIL node, always black, as the child of every leaf, which removes a great many null checks from the fix-up code. In C that is safe because the fix-up writes only to real nodes. In JavaScript people transcribe the algorithm faithfully and then, in the delete fix-up, assign to the sentinel parent, which is legal and silently corrupts every leaf in the tree at once because they are all the same object. The symptom appears much later as a traversal that loops or skips, and it is almost impossible to find by reading the delete code, because the line that does the damage looks correct. Either use null, or freeze the sentinel and let the assignment throw in strict mode.
How does Red-Black Tree actually perform in JavaScript?
Node objects are individually allocated and pointer-chased, the worst case for the cache. Assign every field in the constructor so V8 keeps one hidden class across all nodes and the property loads stay monomorphic. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.