Red Black Tree
RED BLACK TREE
Properties
- Root is always black
- No red nodes are adjacent to each other
- Number of black nodes from any node to a NULL node is the same
Insertion Algorithm
N = new node
P = N's parent
U = N's uncle
GP = N's grandparent
1 Do BST insertion
2 Mark N as red
3 If N is root, colour it black
4 If P is black, stop.
5 Else
6 IF if U is RED,
2 Mark N as red
3 If N is root, colour it black
4 If P is black, stop.
5 Else
6 IF if U is RED,
7 do recolouring (colour P and U as BLACK, and. GP as RED)
8 recursive recolouring by N = GP in the recolouring algorithm and so on
9 IF U is BLACK
10 do Rotation
Rotation Cases
1. Left Left (N is P's left child, P is GP's left child)
2. Right Right (N is P's right child, P is GP's right child)
3. Left Right (N is P's right child, P is GP's left child)
4. Right Left (N is P's left child, P is GP's right child)
Solving the Cases
1. LL: do right rotation on GP as pivot, swap GP and P colours
2. RR: do left rotation on GP as pivot, swap GP and P colours
3. LR: do right rotation on P as pivot, do left rotation with on GP as pivot, swap GP and N colours
4. RL: do left rotation on P as pivot, do right rotation on GP as pivot, swap GP and N colours
Deletion Algorithm
N = node to be deleted
P = parent
S = sibling of N
S = sibling of N
1 Do BST deletion
2 IF N is red, just delete
3 IF N is black and N's child is RED, swap colours and delete N
4 ELSE move to double black case
5 IF N is root, just delete
6. IF P is red and S and S's children are all black, swap P and S colours and immediately delete N
7. IF S is RED, do rotation with P as pivot, swap P and S colours, do second IF
8 IF P, S and S's children are all black, make S red and the the 3rd IF
9. IF S's children is at least one red, do a single/double rotation, the node taking the position of P will also have its colour, delete N
2 IF N is red, just delete
3 IF N is black and N's child is RED, swap colours and delete N
4 ELSE move to double black case
5 IF N is root, just delete
6. IF P is red and S and S's children are all black, swap P and S colours and immediately delete N
7. IF S is RED, do rotation with P as pivot, swap P and S colours, do second IF
8 IF P, S and S's children are all black, make S red and the the 3rd IF
9. IF S's children is at least one red, do a single/double rotation, the node taking the position of P will also have its colour, delete N
Comments
Post a Comment