Skip to main content

Left Leaning Red-Black BSTs (LLRB tree)

Red-Black Tree

  • Represent 2-3 tree as a BST
  • Use internal left-leaning links as glue for 3-nodes

image

Properties

  • No node has two red links connected to it
  • Every path from root to null link has the same number of black links
  • Red links lean left

Operations

image

Implementation

image

image

image

image

image

Color flip - Recolor to split a (temporary) 4-node

image

image

Insertion in a LLRB tree

Basic Strategy

image

Insert into a tree with exactly 1 node

image

  • Insert into a 2-node at the bottom
    • Do standard BST insert; color new link red
    • If new red link is a right link, rotate left

image

Insert into a tree with exactly 2 nodes

image

  • Insert into a 3-node at the bottom
    • Do standard BST insert; color new link red
    • Rotate to balance the 4-node
    • Flip colors to pass red link up one level
    • Rotate to make lean left
    • Repeat case 1 or case 2 up the tree

image

image

Insertion Code

image

If implemented properly, the height of a red-black BST with N keys is at most 2 lg N

image

Applications

Red-black trees are widely used as system symbol tables

  • Java: Java.util.TreeMap, java.util.TreeSet
  • C++ STL: map, multimap, multiset
  • Linux kernel: completely fair scheduler, linux/rbtree.h
  • Emacs: conservative stack scanning