140 likes | 285 Views
Red-black Trees . Consider a b-tree of order 4. A node must have at least 2 children and as many as 4. A node must have at least 1 key value and as many as 3. We have always represented the key values as an array, but what if we did it as a tree?. Red-black Trees Example.
E N D
Red-black Trees • Consider a b-tree of order 4. • A node must have at least 2 children and as many as 4. • A node must have at least 1 key value and as many as 3. • We have always represented the key values as an array, but what if we did it as a tree?
Red-black Trees Example • This is a valid b-tree of order 4; Now store key values in a binary search tree: 180, 260, 550 120, 150 200 440, 500 600
Red-black Trees Example 260 • OK, now link up b-tree node pointers to create a binary search tree: 180 550 150 200 440 600 120 500
Red-black Trees Example 260 • Now color inter-node links black and intra-nodes red: 180 550 150 200 440 600 120 500
Red-black Trees Example 260 • Color each node the color of the edge incident on it: 180 550 150 200 440 600 120 500
Red-black Trees Example 260 • This is a Red-black Tree. It is a height-balanced binary search tree. 180 550 150 200 440 600 120 500
Red-black Properties • A red node must have only black nodes as children. • A black node may have either red or black nodes as children. • The path from the root to any terminal level node must pass through the same number of black nodes.
Red-black Insert • The insert algorithm follows the rules for b-trees, but defines it in terms of node color: • Search for place to insert; All new insertions go in as red nodes. (E.G. All insertions go into an existing b-tree node). • If parent of new node is black, stop. (E.G. If the b-tree node is not full, no problem). • If parent is red, see if a simple AVL-type rotation will work: look at grandparent as root of rotation.
Red-black Insert II • If rotation doesn’t work, move the nearest black ancestor to its parent by making it red and both of its children black. (e.g. split the B-tree node & move middle key to parent). • Repeat for newly colored red node. (e.g. repeat for parent B-tree node).
Red-black Delete • Same basic idea: • Find key to delete; • If it is not at the terminal level, replace with its in order successor & delete this value. • Thus, all deletions which reduce the number of nodes occur at the terminal level of the B-tree. • The rules follow those for deleting from a B-tree:
Red-black Delete II • If the node is red, do your standard BST delete (e.g. the B-tree node is not empty). • If the node is black, but has a red child, do your standard BST delete & make the red child black (e.g. again, B-tree node is not empty). • If the node is black and has no children…
Red-black Delete III • …Attempt to “borrow” from parent’s other child. • …Failing that, “combine” nodes and repeat at (B-tree) parent.