Red-black Trees
description
Transcript of Red-black Trees
1
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?
2
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
440, 500120, 150 200 600
3
Red-black Trees Example
OK, now link up b-tree node pointers to create a binary search tree:
260550180
440500
200150120
600
4
Red-black Trees Example
Now color inter-node links black and intra-nodes red:
260550180
440500
200150120
600
5
Red-black Trees Example
Color each node the color of the edge incident on it:
260550180
440500
200150120
600
6
Red-black Trees Example
This is a Red-black Tree. It is a height-balanced binary search tree.
260550180
440500
200150120
600
7
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.
8
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.
9
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).
10
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:
11
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…
12
Red-black Delete III
…Attempt to “borrow” from parent’s other child.
…Failing that, “combine” nodes and repeat at (B-tree) parent.
13
The End Slide