Aoa PPT Final
Aoa PPT Final
30
15
7
35
5 20 40
8 13
3
Time complexity of Red Black Tree
1. Search O(log n)
2. Insert O(log n)
3. Delete O(log n)
Red Black Tree
Algorithm:
searchElement (tree, val)
Step 1:
If tree -> data = val OR tree = NULL
Return tree
Else
If val data
Return searchElement (tree -> left, val)
Else
Return searchElement (tree -> right, val)
[ End of if ] [ End of if]
Red Black Tree
Example:
Red Black Tree
Red black tree (Insertion)
-While inserting a new node, the new node is always inserted as a RED node.
-After insertion of a new node, if the tree is violating the properties of the red-black tree then,
-we do the following operations.
Recolor
10
Rotation.
The following tree is the suitably inserted 7 16
O(log n)
NIL
Average and Worst case Space complexity.
18 30
O(n)
8 10
8 12
2 4
11 13
6 9
1 3 5
In this its violates the rule it follows All the rules of RBT
10 10
Of RBT.
Red black tree ( Rotations)
There are two rotations.
2– Right rotation.
Basic operations associated with Red Black Tree:
18
8
Insert(5). Insert(15)
8
5 18
18
2 consecutive red nodes, new node
5
15
parent sibling is red & parent’s parent
is root so here we have to recolor to
make it red black tree.
8
After recolor
5 18
15
Insert (17). Here Case 2 implemented.
8
8
5
18
8
18
Left Rotation.
17
15
17 15
15
18
Insert (25). Case 1 implemented,
8
25
5 17
after recolor
15 18
.
Things to remember for deletion
1) Follow BST deletion
2) Last node is always deleted,
Node with children are replaced
3) Node color stays the same
4) If a black node replaces black node
->it will become DB
5) If a red node (black node)replaces black node(red node)
->It will become single black
.
Case 1)D is red 10 Delete 10 7
Do nothing
5 15 5 15
2 7 13 17
2 13 17
Case 2) if DB is root 10 10
->Remove DB
5 15 5 15
2 7 13 2 7 13
17 17
Case 3)if S is red
->swap color P>S
-> Rotate P in DB direction
-> reapply cases
10 15
10
10
Del 5 N 15 10 17
N 15
15
5
13 17 N
17 13 17 13
13
Case 3.2 ) If s is black,SL,ST black
->Remove DB
15 15
->Add black to P
->make S red
->if Db exits, reapply cases
10 17 10 17
N 13 13
15
15 15 15
DEL 17
10 N
10 17 10 N 13 N
13
13 13 10
Case 3.4) If S is black ,SL is red
->rotate p in DB direction
->swap color p<- ->s
->Remove DB
->change color SL to black
13 13
15
15
10 15
13 N 13 N 15
10
N
10 10 N