next up previous
Next: Up: Previous:

Pseudocode

RB-Insert(T,x)
   Insert(T,x)
   color(x) = Red
   while x <> root(T) and color(parent(x)) = Red
      if parent(x) = left(parent(parent(x)))
      then uncle = right(parent(parent(x)))
         if color(uncle) = Red
         then color(parent(x)) = Black                     ; Case I
              color(uncle) = Black
              color(parent(parent(x))) = Red
              x = parent(parent(x))
         else if x = right(parent(x))
              then x = parent(x)                           ; Case II
                   Left-Rotate(T,x)
              color(parent(x)) = Black                     ; Case III
              color(parent(parent(x)) = Red
              Right-Rotate(T, parent(parent(x)))
      else
         ...  ; same as then with "right" and "left" swapped
   color(root(x)) = Black

The performance of this algorithm is O(lgn), with $\leq$ 2 rotations

RBT Example


next up previous
Next: Up: Previous: