Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Red-Black Tree Implementation in JavaScript

19 min readadvanced
Website QA and SEO audits

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

A red-black tree is a binary search tree that colours every node red or black and maintains a small set of invariants: the root is black, a red node never has a red child, and every path from a given node down to a leaf passes through the same number of black nodes. Together those guarantee the longest path is at most twice the shortest, which bounds the height at roughly twice the base-two logarithm of the number of entries. That is a looser bound than an AVL tree maintains, and it is deliberate: a red-black tree does fewer rotations per insertion and deletion, so it trades a little search speed for a lot of write speed. That trade is why it, and not the AVL tree, is the structure standard libraries actually ship, and the most useful thing to know about it in any given language is whether the ordered collection you already use is one.

Red-Black Tree in JavaScript: what you actually reach for

None. Map is a hash table that iterates in insertion order, and there is no ordered collection in the language.

JavaScript implementation

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.
javascript
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 Free

The JavaScript-specific 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. 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.

Performance in JavaScript, beyond the O(log n)

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. The asymptotic cost is the same in every language, O(log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Red-Black Tree between languages.

Real-World Applications

Red-Black Tree applies wherever its problem shape appears in your own code. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Red-Black Tree helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Red-Black Tree appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Red-Black Tree over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Red-Black Tree to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.