next up previous
Next: Deletion Up: CSE 2320: Algorithms and Previous: Case III: x's uncle

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

Insertion Example



Copyright © 1998 The University of Texas at Arlington