SlideShare a Scribd company logo
1 of 33
RED-BLACK TREE
INTRODUCTION
 A balancing binary search tree.
 A data structure requires an extra one bit color field
in each node which is red or black.
 Leonidas J. Guibas and Robert Sedgewick derived
the red-black tree from the symmetric binary B-tree.
EXAMPLE OF RED BLACK TREE
PROPERTIES OF RED BLACK TREE
 The root and leaves (NIL’s) are black.
 A RED parent never has a RED child.
 in other words: there are never two successive RED nodes in
a path
 Every path from the root to an empty subtree contains the same
number of BLACK nodes
 called the black height
 We can use black height to measure the balance of a red-black
tree.
RED BLACK TREE OPERATIONS
Average
Space O(n)
Search
O(log2 n)
Traversal *O(n)
Insertion
O(log2 n)
Deletion
O(log2 n)
RED BLACK TREES: ROTATION
 Basic operation for changing tree structure is called
rotation:
RB TREES: ROTATION
x
y
y
x
 A lot of pointer manipulation
 x keeps its left child
 y keeps its right child
 x’s right child becomes y’s left child
 x’s and y’s parents change
A B
C A
B C
ROTATION ALGORITHM
LEFT-ROTATE(T, x)
y ← x->right
x->right← y->left
y->left->p ← x
y->p ← x->p
if x->p = Null
then T->root ← y
else if x = x->p->left
then x->p->left ← y
else x->p->right ← y
y->left ← x
x->p ← y
RIGHT-ROTATE(T, x)
y ← x->left
x->left← y->right
y->right->p ← x
y->p ← x->p
if x->p = Null
then T->root ← y
else if x = x->p->right
then x->p->right ← y
else x->p->left ← y
y->right ← x
x->p ← y
Runtime : O(1) for Both.
ROTATION EXAMPLE
 Rotate left about 9:
12
5 9
7
8
11
ROTATION EXAMPLE
 Rotate left about 9:
5 12
7
9
118
RED-BLACK TREES: INSERTION
 Insertion: the basic idea
 Insert x into tree, color x red
 Only r-b property 3 might be violated (if p[x] red)
 If so, move violation up tree until a place is found where it can
be fixed
 Total time will be O(log n)
Insertion Algorithm
TreeNode<T> rbInsert(TreeNode<T> root,TreeNode<T> x)// returns a new root
{
root=bstInsert(root,x); // a modification of BST insertItem
x.setColor(red);
while (x != root and x.getParent().getColor() == red) {
if (x.getParent() == x.getParent().getParent().getLeft()) {
//parent is left child
y = x.getParent().getParent().getRight() //uncle of x
if (y.getColor() == red) {// uncle is red
x.getParent().setColor(black);
y.setColor(black);
x.getParent().getParent().setColor(red);
x = x.getParent().getParent();
} else { // uncle is black
if (x == x.getParent().getRight()) {
x = x.getParent();
root = left_rotate(root,x);
}
x.getParent().setColor(black);
x.getParent().getParent().setColor(red);
root = right_rotate(root,x.getParent().getParent());
}}
} else
// ... symmetric to if
} // end while
root.setColor(black);
return root;
}
RB INSERT: CASE 1
B
 
x
● Case 1: “uncle” is red
● In figures below, all ’s are
equal-black-height
subtrees
C
A D
  
C
A D
 
y
new x
Same action whether x is a left or a right child
B
 
x
case 1
RB INSERT: CASE 2
B
 
x
● Case 2:
■ “Uncle” is black
■ Node x is a right child
● Transform to case 3 via a left-rotation
C
A 
C
By
A
 
x 
case 2

y
Transform case 2 into case 3 (x is left child) with a left rotation
This preserves property 4: all downward paths contain same number of black nodes
RB INSERT: CASE 3
● Case 3:
■ “Uncle” is black
■ Node x is a left child
● Change colors; rotate right
B
Ax

case 3
C
B
A
 
x 
y C
 
Perform some color changes and do a right rotation
Again, preserves property 4: all downward paths contain same number of black nodes
RB INSERT: CASES 4-6
 Cases 1-3 hold if x’s parent is a left child
 If x’s parent is a right child, cases 4-6 are symmetric
(swap left for right)
INSERTION EXAMPLE
Insert 65
47
7132
93
INSERTION EXAMPLE
Insert 65
47
7132
65 93
INSERTION EXAMPLE
Insert 65
47
7132
65 93
Insert 82
INSERTION EXAMPLE
82
Insert 65 47
7132
65 93
Insert 82
INSERTION EXAMPLE
82
Insert 65
47
7132
65 93
Insert 82
65
71
93
change nodes’ colors
INSERTION EXAMPLE
9365
71
82
Insert 65
47
32
Insert 82
Insert 87
87
INSERTION EXAMPLE
9365
71
82
Insert 65
47
32
Insert 82
Insert 87
87
INSERTION EXAMPLE
9365
71
87
Insert 65
47
32
Insert 82
Insert 87
82
INSERTION EXAMPLE
9365
87
Insert 65
47
32
Insert 82
Insert 87
82
71
87
93
change nodes’ colors
INSERTION EXAMPLE
87
93
65
Insert 65
47
32
Insert 82
Insert 87
82
71
RB TREE DELETION ALGORITHM
TreeNode<T> rbDelete(TreeNode<T> root,TreeNode<T> z)
//return new root, z contains item to be deleted
{
TreeNode<T> x,y;
// find node y, which is going to be removed
if (z.getLeft() == null || z.getRight() == null)
y = z;
else {
y = successor(z); // or predecessor
z.setItem(y.getItem); // move data from y to z
}
// find child x of y
if (y.getRight() != null)
x = y.getRight();
else
x = y.getLeft();
// Note x might be null; create a pretend node
if (x == null) {
x = new TreeNode<T>(null);
x.setColor(black);
}
RED-BLACK TREE RETRIEVAL:
 Retrieving a node from a red-black tree doesn’t
require more than the use of the BST procedure,
which takes O(log n) time.
RB TREES EFFICIENCY
 All operations work in time O(height)
 and we have proved that heigh is O(log n)
 hence, all operations work in time O(log n)! – much
more efficient than linked list or arrays implementation of
sorted list!
RED BLACK TREE APPLICATION
 Completely Fair Scheduler in Linux Kernel.
 Computational Geometry Data structures.
 Red-black trees make less structural changes to balance
themselves .
 To keep track of the virtual memory segments for a process -
the start address of the range serves as the key.
 Red–black trees are also particularly valuable in functional
programming
To keep track of the virtual memory segments for a process - the
start address of the range serves as the key.
COMPARISON BETWEEN AVL AND RB TREE
 For small data:
 insert: RB tree & avl tree has constant number of max
rotation but RB tree will be faster because on average
RB tree use less rotation.
 lookup: AVL tree is faster, because AVL tree has less
depth.
 delete: RB tree has constant number of max rotation but
AVL tree can have O(log N) times of rotation as worst.
and on average RB tree also has less number of
rotation thus RB tree is faster.
COMPARISON BETWEEN AVL AND RB TREE
(CONTINUED)
 for large data:
 insert: AVL tree is faster. because you need to lookup for a
particular node before insertion. as you have more data the time
difference on looking up the particular node grows proportional to
O(log N). but AVL tree & RB tree still only need constant number
of rotation at the worst case. Thus the bottle neck will become
the time you lookup for that particular node.
 lookup: AVL tree is faster. (same as in small data case)
 delete: AVL tree is faster on average, but in worst case RB tree is
faster. because you also need to lookup for a very deep node to
swap before removal (similar to the reason of insertion). on
average both trees has constant number of rotation. but RB tree
has a constant upper bound for rotation.
Thank
You

More Related Content

What's hot

B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
Anuj Modi
 

What's hot (20)

Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
Tree Traversal Algorithm in Data Structure
Tree Traversal Algorithm in Data StructureTree Traversal Algorithm in Data Structure
Tree Traversal Algorithm in Data Structure
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Red black tree
Red black treeRed black tree
Red black tree
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
 
Counting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort AlgorithmsCounting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort Algorithms
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
AVL Tree in Data Structure
AVL Tree in Data Structure AVL Tree in Data Structure
AVL Tree in Data Structure
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 

Viewers also liked

Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithms
Aakash deep Singhal
 

Viewers also liked (20)

Balanced Tree(AVL Tree,Red Black Tree)
Balanced Tree(AVL Tree,Red Black Tree)Balanced Tree(AVL Tree,Red Black Tree)
Balanced Tree(AVL Tree,Red Black Tree)
 
Bermuda Triangle
Bermuda TriangleBermuda Triangle
Bermuda Triangle
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Academic Pressure Too Much To Handle
Academic Pressure Too Much To HandleAcademic Pressure Too Much To Handle
Academic Pressure Too Much To Handle
 
Sudoku
SudokuSudoku
Sudoku
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
Red black trees1109
Red black trees1109Red black trees1109
Red black trees1109
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Karnaugh Graph or K-Map
Karnaugh Graph or K-MapKarnaugh Graph or K-Map
Karnaugh Graph or K-Map
 
Lecture 9 data structures and algorithms
Lecture 9 data structures and algorithmsLecture 9 data structures and algorithms
Lecture 9 data structures and algorithms
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Traversals | Data Structures
Traversals | Data StructuresTraversals | Data Structures
Traversals | Data Structures
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Tree
TreeTree
Tree
 
Binary Search Algorithm
Binary Search Algorithm Binary Search Algorithm
Binary Search Algorithm
 
Tree
TreeTree
Tree
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Tree (Data Structure & Discrete Mathematics)
Tree (Data Structure & Discrete Mathematics)Tree (Data Structure & Discrete Mathematics)
Tree (Data Structure & Discrete Mathematics)
 

Similar to Red Black Tree

lecture 14
lecture 14lecture 14
lecture 14
sajinsc
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
Umang Gupta
 
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.pptUnit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Sheba41
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
zukun
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
Extend your work on the OCC logo to add shapes that curve1 the blue.pdf
Extend your work on the OCC logo to add shapes that curve1 the blue.pdfExtend your work on the OCC logo to add shapes that curve1 the blue.pdf
Extend your work on the OCC logo to add shapes that curve1 the blue.pdf
arihantcommunication
 

Similar to Red Black Tree (20)

Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
 
Red black trees
Red black treesRed black trees
Red black trees
 
lecture 14
lecture 14lecture 14
lecture 14
 
16 rbtrees
16 rbtrees16 rbtrees
16 rbtrees
 
Red black tree
Red black treeRed black tree
Red black tree
 
rbtrees.ppt
rbtrees.pptrbtrees.ppt
rbtrees.ppt
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.pptUnit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
 
Trees
TreesTrees
Trees
 
Red black trees
Red black treesRed black trees
Red black trees
 
Data structures final lecture 1
Data structures final  lecture 1Data structures final  lecture 1
Data structures final lecture 1
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
 
Cse 225 rbt_red_black_tree
Cse 225 rbt_red_black_treeCse 225 rbt_red_black_tree
Cse 225 rbt_red_black_tree
 
Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy Collections
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Refined types (FP-Syd)
Refined types (FP-Syd)Refined types (FP-Syd)
Refined types (FP-Syd)
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Extend your work on the OCC logo to add shapes that curve1 the blue.pdf
Extend your work on the OCC logo to add shapes that curve1 the blue.pdfExtend your work on the OCC logo to add shapes that curve1 the blue.pdf
Extend your work on the OCC logo to add shapes that curve1 the blue.pdf
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 

Red Black Tree

  • 2. INTRODUCTION  A balancing binary search tree.  A data structure requires an extra one bit color field in each node which is red or black.  Leonidas J. Guibas and Robert Sedgewick derived the red-black tree from the symmetric binary B-tree.
  • 3. EXAMPLE OF RED BLACK TREE
  • 4. PROPERTIES OF RED BLACK TREE  The root and leaves (NIL’s) are black.  A RED parent never has a RED child.  in other words: there are never two successive RED nodes in a path  Every path from the root to an empty subtree contains the same number of BLACK nodes  called the black height  We can use black height to measure the balance of a red-black tree.
  • 5. RED BLACK TREE OPERATIONS Average Space O(n) Search O(log2 n) Traversal *O(n) Insertion O(log2 n) Deletion O(log2 n)
  • 6. RED BLACK TREES: ROTATION  Basic operation for changing tree structure is called rotation:
  • 7. RB TREES: ROTATION x y y x  A lot of pointer manipulation  x keeps its left child  y keeps its right child  x’s right child becomes y’s left child  x’s and y’s parents change A B C A B C
  • 8. ROTATION ALGORITHM LEFT-ROTATE(T, x) y ← x->right x->right← y->left y->left->p ← x y->p ← x->p if x->p = Null then T->root ← y else if x = x->p->left then x->p->left ← y else x->p->right ← y y->left ← x x->p ← y RIGHT-ROTATE(T, x) y ← x->left x->left← y->right y->right->p ← x y->p ← x->p if x->p = Null then T->root ← y else if x = x->p->right then x->p->right ← y else x->p->left ← y y->right ← x x->p ← y Runtime : O(1) for Both.
  • 9. ROTATION EXAMPLE  Rotate left about 9: 12 5 9 7 8 11
  • 10. ROTATION EXAMPLE  Rotate left about 9: 5 12 7 9 118
  • 11. RED-BLACK TREES: INSERTION  Insertion: the basic idea  Insert x into tree, color x red  Only r-b property 3 might be violated (if p[x] red)  If so, move violation up tree until a place is found where it can be fixed  Total time will be O(log n)
  • 12. Insertion Algorithm TreeNode<T> rbInsert(TreeNode<T> root,TreeNode<T> x)// returns a new root { root=bstInsert(root,x); // a modification of BST insertItem x.setColor(red); while (x != root and x.getParent().getColor() == red) { if (x.getParent() == x.getParent().getParent().getLeft()) { //parent is left child y = x.getParent().getParent().getRight() //uncle of x if (y.getColor() == red) {// uncle is red x.getParent().setColor(black); y.setColor(black); x.getParent().getParent().setColor(red); x = x.getParent().getParent(); } else { // uncle is black if (x == x.getParent().getRight()) { x = x.getParent(); root = left_rotate(root,x); } x.getParent().setColor(black); x.getParent().getParent().setColor(red); root = right_rotate(root,x.getParent().getParent()); }} } else // ... symmetric to if } // end while root.setColor(black); return root; }
  • 13. RB INSERT: CASE 1 B   x ● Case 1: “uncle” is red ● In figures below, all ’s are equal-black-height subtrees C A D    C A D   y new x Same action whether x is a left or a right child B   x case 1
  • 14. RB INSERT: CASE 2 B   x ● Case 2: ■ “Uncle” is black ■ Node x is a right child ● Transform to case 3 via a left-rotation C A  C By A   x  case 2  y Transform case 2 into case 3 (x is left child) with a left rotation This preserves property 4: all downward paths contain same number of black nodes
  • 15. RB INSERT: CASE 3 ● Case 3: ■ “Uncle” is black ■ Node x is a left child ● Change colors; rotate right B Ax  case 3 C B A   x  y C   Perform some color changes and do a right rotation Again, preserves property 4: all downward paths contain same number of black nodes
  • 16. RB INSERT: CASES 4-6  Cases 1-3 hold if x’s parent is a left child  If x’s parent is a right child, cases 4-6 are symmetric (swap left for right)
  • 20. INSERTION EXAMPLE 82 Insert 65 47 7132 65 93 Insert 82
  • 21. INSERTION EXAMPLE 82 Insert 65 47 7132 65 93 Insert 82 65 71 93 change nodes’ colors
  • 25. INSERTION EXAMPLE 9365 87 Insert 65 47 32 Insert 82 Insert 87 82 71 87 93 change nodes’ colors
  • 27. RB TREE DELETION ALGORITHM TreeNode<T> rbDelete(TreeNode<T> root,TreeNode<T> z) //return new root, z contains item to be deleted { TreeNode<T> x,y; // find node y, which is going to be removed if (z.getLeft() == null || z.getRight() == null) y = z; else { y = successor(z); // or predecessor z.setItem(y.getItem); // move data from y to z } // find child x of y if (y.getRight() != null) x = y.getRight(); else x = y.getLeft(); // Note x might be null; create a pretend node if (x == null) { x = new TreeNode<T>(null); x.setColor(black); }
  • 28. RED-BLACK TREE RETRIEVAL:  Retrieving a node from a red-black tree doesn’t require more than the use of the BST procedure, which takes O(log n) time.
  • 29. RB TREES EFFICIENCY  All operations work in time O(height)  and we have proved that heigh is O(log n)  hence, all operations work in time O(log n)! – much more efficient than linked list or arrays implementation of sorted list!
  • 30. RED BLACK TREE APPLICATION  Completely Fair Scheduler in Linux Kernel.  Computational Geometry Data structures.  Red-black trees make less structural changes to balance themselves .  To keep track of the virtual memory segments for a process - the start address of the range serves as the key.  Red–black trees are also particularly valuable in functional programming To keep track of the virtual memory segments for a process - the start address of the range serves as the key.
  • 31. COMPARISON BETWEEN AVL AND RB TREE  For small data:  insert: RB tree & avl tree has constant number of max rotation but RB tree will be faster because on average RB tree use less rotation.  lookup: AVL tree is faster, because AVL tree has less depth.  delete: RB tree has constant number of max rotation but AVL tree can have O(log N) times of rotation as worst. and on average RB tree also has less number of rotation thus RB tree is faster.
  • 32. COMPARISON BETWEEN AVL AND RB TREE (CONTINUED)  for large data:  insert: AVL tree is faster. because you need to lookup for a particular node before insertion. as you have more data the time difference on looking up the particular node grows proportional to O(log N). but AVL tree & RB tree still only need constant number of rotation at the worst case. Thus the bottle neck will become the time you lookup for that particular node.  lookup: AVL tree is faster. (same as in small data case)  delete: AVL tree is faster on average, but in worst case RB tree is faster. because you also need to lookup for a very deep node to swap before removal (similar to the reason of insertion). on average both trees has constant number of rotation. but RB tree has a constant upper bound for rotation.