Red-Black Tree

A self-balancing binary search tree with color properties that ensure the tree remains approximately balanced. Guarantees logarithmic time operations.

Red-Black Tree Visualization

SlowFast
🔊 Sound
ReadyEmpty Red-Black Tree. Insert a value.
Red NodeBlack Node Search path FoundEdge → red childEdge → black child
empty tree — insert a value

Complexity

Time Complexity: O(log n)
Space Complexity: O(n)

Pseudocode

function insert(root, key):
  node = standard BST insert
  color node red
  while node != root and node.parent is red:
    if parent is left child:
      uncle = parent.parent.right
      if uncle is red:
        recolor parent, uncle, grandparent
        node = grandparent
      else:
        if node is right child:
          node = parent
          rotateLeft(node)
        recolor parent and grandparent
        rotateRight(grandparent)
    else:
      (mirror case)
  color root black