Red-Black trees Red-black trees are trees represented as binary trees at the expense of one extra bit per node. The idea is to represent 3- and 4-nodes as mini- binary trees, bound by “red” links. Red-black trees have the following properties: 13-nodes can be represented in two different ways. 2Two red links never follow one another in a row. 3All paths in the red-black tree have the same number of black links. 4One path containing red and black links can be twice as long as another path containing only black links. 5All path lengths are proportional to log N. 6Nodes with data items equal to a given node can fall on both sides of that node.
Examples OR
Operations on red-black trees Search: same as in binary search trees, except for the need of a boolean attribute black that each node must maintain. Insert: same as in trees, except that the colors of the links must be taken into consideration. Delete: similar to deletion in binary search trees. We can always delete a node that has at least one external child. However, if the key to be deleted is stored in a node with no external children, we move there the key of its inorder predecessor (or successor), and delete that node instead. Example:
Insert operation: example Insert Split 12
Splitting 4-nodes without rotation Case1: Splitting a 4-node connected to a 2-node
Splitting 4-nodes without rotation (contd.) Case2A: Splitting a 4-node connected to a 3-node
Splitting 4-nodes with single rotation Case2B: Splitting a 4-node connected to a 3-node
Splitting 4-nodes with double rotation Case2C: Splitting a 4-node connected to a 3-node Reduced to case 2B
The insertRB method Algorithm insertRB (T, newData, precedes) boolean success := false if (T = null) { NodeRBtree node = new NodeRBtree(newData) success := true } else { if (nodeType(T)= 4) splitroot(T) NodeRBtree p := T; NodeRBtree parent := null; boolean done := false while (! done) { if (nodeType(p) = 4) { if (nodeType (parent) = 2) then splitChildOf2 (p, parent) else splitChildOf3 (p, parent) } int compareResult := compare (p, newData, precedes) if (compareResult < 0) then success := false; done := true else if (compareResult = 0) then insertData (p, newData, precedes); success:=true; done:=true else advance (p, parent, compareResult) } // end while } // end else