Skip to Content
Learning JavaScript Data Structures and Algorithms - Third Edition
book

Learning JavaScript Data Structures and Algorithms - Third Edition

by Loiane Avancini
April 2018
Beginner to intermediate content levelBeginner to intermediate
426 pages
10h 19m
English
Packt Publishing
Content preview from Learning JavaScript Data Structures and Algorithms - Third Edition

Inserting a node in the Red-Black tree

Inserting a node in a Red-Black tree works the same way as in BST. In addition to inserting the code, we will also apply a color to the node and after the insertion, we will verify whether the tree still meets the rules of the Red-Black tree and that it is still balanced.

The following code inserts a new node in a Red-Black tree:

insert(key: T) {
  if (this.root == null) { // {1}
    this.root = new RedBlackNode(key); // {2}
    this.root.color = Colors.BLACK; // {3}
  } else {
    const newNode = this.insertNode(this.root, key); // {4}
    this.fixTreeProperties(newNode); // {5}
  }
}

If the tree is empty ({1}), then we will create a new Red-Black tree node ({2}) and to comply with rule 2, we will set the root color as black ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript Data Structures and Algorithms

Learning JavaScript Data Structures and Algorithms

Loiane Avancini

Publisher Resources

ISBN: 9781788623872Supplemental Content