SlideShare a Scribd company logo
1 of 34
Red Black Trees
Data Structures
Some Properties of Binary Search Tree
• The common properties of binary search trees are as follows:
• The left sub tree of a node contains only nodes with keys less than the node's key.
• The right sub tree of a node contains only nodes with keys greater than the node's
key.
• The left and right sub tree each must also be a binary search tree.
• There must be no duplicate nodes.
• A unique path exists from the root to every other node.
Problem with Binary Search Tree
• Binary Search Tree is fast in insertion and deletion etc. when balanced.
• Time Complexity of performing operations (e.g. searching , inserting , deletion etc) on
binary search tree is O(logn) in best case i.e when tree is balanced.
• And on the other hand performance degrades from O(logn) to O(n) when tree is not
balanced.
• Basic binary search trees have three very nasty degenerate cases where the structure
stops being logarithmic and becomes a glorified linked list.
• The two most common of these degenerate cases is ascending or descending sorted
order (the third is outside-in alternating order).
Problem with Binary Search Tree
1
2
3
4
6
5
3
4
9
2
6
5
7
Alternating OrderDescending OrderAscending order
Red Black Tree
• A red-black tree is a balanced binary search tree with one extra bit of storage per node:
its color, which can be either Red or Black.
• By constraining the node colors on any simple path from the root to a leaf, red-black
trees ensure that no such path is more than twice as long as any other, so that the tree
is approximately balanced.
• Each node of the tree now contains the attributes color, key, left, right, and p.
• If a child or the parent of a node does not exist, the corresponding pointer attribute of
the node contains the value NIL.
Properties of Red Black Tree
A red-black tree is a binary tree that satisfies the
following red-black properties:
1. Every node is either red or black.
2. The root is black.
3. Every leaf (NIL) is black.
4. If a node is red, then both its children are
black.
5. For each node, all simple paths from the
node to descendant leaves contain the same
number of black nodes.
Nil
• The search-tree operations TREE-INSERT and TREE-DELETE, when run on a red black
tree with n keys, take O(log n)time. Because they modify the tree, the result may
violate the red-black properties.
• To restore these properties, we must change the colors of some of the nodes in the
tree and also change the pointer structure.
• We change the pointer structure through rotation, which is a local operation in a
search tree that preserves the binary-search-tree property.
• There are two kinds of rotations : left rotations and right rotations.
Red Black Tree (Rotations)
• When we do a left rotation on a node x, we assume that its right child y is
not null ;x may be any node in the tree whose right child is not null.
Left Rotation
X
Y
α β
ϒ
LEFT-ROTATE (T , x)
1. y = x.right // set y new temporary node
2. x.right = y.left // turn y’s left subtree into x’s
right subtree
3. if y.left != T.nil
4. y.left.p = x
5. y.p= x.p // link x’s parent to y
6. if x.p == T. nil
7. T.root = y
8. else if x == x.p.left
9. x.p.left = y
10.else x.p.right = y
11. y.left = x // put x on y’s left
12. x.p = y
X
Y
α β
ϒ
Right Rotation
Comparison
Insertion
• We can insert a node into an n-node red-black tree in O(logn) time.
• To do so, we use a slightly modified version of the TREE-INSERT procedure to
insert node into the tree T as if it were an ordinary binary search tree.
• Then we color it to red.
• To guarantee that the red-black properties are preserved, we then call an
auxiliary procedure RB-INSERT-FIXUP to recolor nodes and perform rotations.
Insertion
Insertion
RB-INSERT(T, z)
1. y ← T.nil
2. x ← T.root
3. while x ≠ T.nil
4. y = x
5. if z.key < x.key
6. then x ← x.left
7. else x ← x.right
8. z.p = y
9. if y = T.nil
10. then T.root ← z
11. else if z.key< y.key
12. then y.left ← z
13. else y.right ← z
14. z.left ← T.nil
15. z.right ← T.nil
16. z.color← RED
17. RB-INSERT-FIXUP(T, z)
Insertion
The procedures TREE-INSERT and RB-INSERT differ in four ways.
• First, all instances of NIL in TREE-INSERT are replaced by T.nil.
• Second, we set z.left and z.right to T. nil in lines 14–15 of RB-INSERT, in order to
maintain the proper tree structure.
• Third, we color z red in line 16.
• Fourth, because coloring z.red may cause a violation of one of the red-black
properties, we call RB-INSERT-FIXUP(T,z) in line 17 of RB-INSERT to restore the
red-black properties
Insertion
• Case 1. z's uncle y is red
• Case 2. z's uncle y is black and z is a right child
• Case 3. z's uncle y is black and z is a left child
Insertion
Insertion
Insertion
Insertion
Case3: z's uncle y is black and z is a left childCase2: z's uncle y is black and z is a right child
Insertion
RB-INSERT-FIXUP(T, z)
1. while z.p.color == RED
2. if z.p == z.p.p.left
3. then y ← z.p.p.right
4. if y.color== RED
5. then z.p.color← BLACK //Case 1
6. y.color ← BLACK //Case 1
7. z.p.p.color← RED //Case 1
8. z ← z.p.p // Case 1
9. else if z = z.p.right
10. then z ← z.p //Case 2
11. LEFT-ROTATE(T, z) //Case 2
12. z.p .color← BLACK //Case 3
13. z.p .p.color← RED //Case 3
14. RIGHT-ROTATE(T, z.p .p) // Case 3
15. else .same as then clause with "right" an= "left" exchange=)
16. T.root.color← BLACK
Insertion
• To understand how RB-INSERT-FIXUP works, we shall break our examination of
the code into three major steps.
• First, we shall determine what violations of the red-black properties are
introduced in RB-INSERT when node z is inserted and colored red.
• Second, we shall examine the overall goal of the while loop in lines 1–15.
• Finally, we shall explore each of the three cases within the while loop’s body and
see how they accomplish the goal.
Insertion
• The while loop in lines 1–15 maintains the following three-part invariant.
• At the start of each iteration of the loop,
a) Node z is red.
b) If z.p is the root, then z.p is black.
c) If there is a violation of the red-black properties , there is at most one violation, and it is of
either property 2 or property 4. If there is a violation of property 2, it occurs because z is the
root and is red. If there is a violation of property 4, it occurs because both z and z.p are red.
Deletion
• Like the other basic operations on an Red Black tree, deletion of a node takes time
O(logn)
• Deleting a node from a red-black tree is a bit more complicated than inserting a node.
• The procedure for deleting a node from a red-black tree is based on the RB-DELETE
procedure
• First, we need to customize the TRANSPLANT subroutine that RB-DELETE calls so that it
applies to a red-black tree.
Deletion
RB-TRANSPLANT(T.u.v)
1. if u.p == T.nil
2. T.root = v
3. elseif u == u.p.left
4. u.p.left = v
5. else u.p.right = v
6. v.p = u.p
Deletion
RB-DELETE (T,z)
1. y = z
2. y-original-color = y.color
3. if z.left = = T. nil
4. x = z. right
5. RB-TRANSPLANT (T, z, z. right)
6. elseif z. right = = T. nil
7. x = z. left
8. RB-TRANSPLANT(T, z, z. left)
9. else y = TREE-MINIMUM(z. right)
10. y-original-color = y. color
11. x = y. right
12. if y. p = = z
13. x. p = y
Deletion
14. else RB-TRANSPLANT(T, y, y. right)
15. y. right = z. right
16. y. right. p = y
17. RB-TRANSPLANT(T, z, y)
18. y. left = z. left
19. y. left. p = y
20. y. color = z. color
21. if y-original-color == BLACK
22. RB-DELETE-FIXUP(T, x)
Deletion
Case 1: x's sibling w is red
Deletion
Case 2: x's sibling w is black, and both of w's children are black
Deletion
Case 3: x's sibling w is black, w's left child is red, and w's right child is black
Deletion
Case 4: x's sibling w is black, and w's right child is red
Deletion
RB-DELETE-FIXUP(T, x)
1. while x !=T.root an= x. color == BLACK
2. if x == x. p. left
3. w = x. p. right
4. if w. color = = RED
5. w. color = BLACK //case 1
6. x. p. color = RED //case 1
7. LEFT-ROTATE(T, x. p) //case 1
8. w = x. p. right //case 1
9. if w. left. color == BLACK and w. right. color = = BLACK
10. w. color = RED //case 2
11. x = x. p //case 2
Deletion
12. else if w. right. color == BLACK
13. w. left. color = BLACK //case 3
14. w. color = RED //case 3
15. RIGHT-ROTATE(T, w) //case 3
16. w = x. p. right //case 3
17. w. color = x. p. color //case 4
18. x. p. color = BLACK //case 4
19. w. right. color = BLACK //case 4
20. LEFT-ROTATE(T, x. p) //case 4
21. x = T. root //case 4
22. else (same as then clause with “right” and “left” exchanged)
23. x. color = BLACK

More Related Content

What's hot

What's hot (20)

Binary Search
Binary SearchBinary Search
Binary Search
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structure
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
Red black trees
Red black treesRed black trees
Red black trees
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
3.9 external sorting
3.9 external sorting3.9 external sorting
3.9 external sorting
 
String matching algorithms
String matching algorithmsString matching algorithms
String matching algorithms
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Backtracking
BacktrackingBacktracking
Backtracking
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Deadlock dbms
Deadlock dbmsDeadlock dbms
Deadlock dbms
 

Viewers also liked

Viewers also liked (11)

Red Black Trees
Red Black TreesRed Black Trees
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
 
Red black trees presentation
Red black trees presentationRed black trees presentation
Red black trees presentation
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithm
 
Binary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red BlackBinary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red Black
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
Algorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class NotesAlgorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class Notes
 
Design & Analysis Of Algorithm
Design & Analysis Of AlgorithmDesign & Analysis Of Algorithm
Design & Analysis Of Algorithm
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 

Similar to Red black trees

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
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
Umang Gupta
 
lecture 14
lecture 14lecture 14
lecture 14
sajinsc
 
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdfanastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
AayushAdhikari27
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
fredharris32
 

Similar to Red black trees (20)

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
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
 
rbtrees.ppt
rbtrees.pptrbtrees.ppt
rbtrees.ppt
 
16 rbtrees
16 rbtrees16 rbtrees
16 rbtrees
 
lecture 14
lecture 14lecture 14
lecture 14
 
Cse 225 rbt_red_black_tree
Cse 225 rbt_red_black_treeCse 225 rbt_red_black_tree
Cse 225 rbt_red_black_tree
 
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdfanastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
 
Red black 1
Red black 1Red black 1
Red black 1
 
Red black tree
Red black treeRed black tree
Red black tree
 
Red Black Tree
Red Black TreeRed Black 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)
Balanced Tree(AVL Tree,Red Black Tree)
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 
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)
 
Data structure
Data structureData structure
Data structure
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Tree
TreeTree
Tree
 
void insertFixUp (Node node) This method recolors and rotates the tree.pdf
void insertFixUp (Node node) This method recolors and rotates the tree.pdfvoid insertFixUp (Node node) This method recolors and rotates the tree.pdf
void insertFixUp (Node node) This method recolors and rotates the tree.pdf
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Red black tree insertion
Red black tree insertionRed black tree insertion
Red black tree insertion
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Red black trees

  • 1. Red Black Trees Data Structures
  • 2. Some Properties of Binary Search Tree • The common properties of binary search trees are as follows: • The left sub tree of a node contains only nodes with keys less than the node's key. • The right sub tree of a node contains only nodes with keys greater than the node's key. • The left and right sub tree each must also be a binary search tree. • There must be no duplicate nodes. • A unique path exists from the root to every other node.
  • 3. Problem with Binary Search Tree • Binary Search Tree is fast in insertion and deletion etc. when balanced. • Time Complexity of performing operations (e.g. searching , inserting , deletion etc) on binary search tree is O(logn) in best case i.e when tree is balanced. • And on the other hand performance degrades from O(logn) to O(n) when tree is not balanced. • Basic binary search trees have three very nasty degenerate cases where the structure stops being logarithmic and becomes a glorified linked list. • The two most common of these degenerate cases is ascending or descending sorted order (the third is outside-in alternating order).
  • 4. Problem with Binary Search Tree 1 2 3 4 6 5 3 4 9 2 6 5 7 Alternating OrderDescending OrderAscending order
  • 5. Red Black Tree • A red-black tree is a balanced binary search tree with one extra bit of storage per node: its color, which can be either Red or Black. • By constraining the node colors on any simple path from the root to a leaf, red-black trees ensure that no such path is more than twice as long as any other, so that the tree is approximately balanced. • Each node of the tree now contains the attributes color, key, left, right, and p. • If a child or the parent of a node does not exist, the corresponding pointer attribute of the node contains the value NIL.
  • 6. Properties of Red Black Tree A red-black tree is a binary tree that satisfies the following red-black properties: 1. Every node is either red or black. 2. The root is black. 3. Every leaf (NIL) is black. 4. If a node is red, then both its children are black. 5. For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
  • 7. Nil
  • 8. • The search-tree operations TREE-INSERT and TREE-DELETE, when run on a red black tree with n keys, take O(log n)time. Because they modify the tree, the result may violate the red-black properties. • To restore these properties, we must change the colors of some of the nodes in the tree and also change the pointer structure. • We change the pointer structure through rotation, which is a local operation in a search tree that preserves the binary-search-tree property. • There are two kinds of rotations : left rotations and right rotations. Red Black Tree (Rotations)
  • 9. • When we do a left rotation on a node x, we assume that its right child y is not null ;x may be any node in the tree whose right child is not null. Left Rotation X Y α β ϒ
  • 10. LEFT-ROTATE (T , x) 1. y = x.right // set y new temporary node 2. x.right = y.left // turn y’s left subtree into x’s right subtree 3. if y.left != T.nil 4. y.left.p = x 5. y.p= x.p // link x’s parent to y 6. if x.p == T. nil 7. T.root = y 8. else if x == x.p.left 9. x.p.left = y 10.else x.p.right = y 11. y.left = x // put x on y’s left 12. x.p = y X Y α β ϒ
  • 13. Insertion • We can insert a node into an n-node red-black tree in O(logn) time. • To do so, we use a slightly modified version of the TREE-INSERT procedure to insert node into the tree T as if it were an ordinary binary search tree. • Then we color it to red. • To guarantee that the red-black properties are preserved, we then call an auxiliary procedure RB-INSERT-FIXUP to recolor nodes and perform rotations.
  • 15. Insertion RB-INSERT(T, z) 1. y ← T.nil 2. x ← T.root 3. while x ≠ T.nil 4. y = x 5. if z.key < x.key 6. then x ← x.left 7. else x ← x.right 8. z.p = y 9. if y = T.nil 10. then T.root ← z 11. else if z.key< y.key 12. then y.left ← z 13. else y.right ← z 14. z.left ← T.nil 15. z.right ← T.nil 16. z.color← RED 17. RB-INSERT-FIXUP(T, z)
  • 16. Insertion The procedures TREE-INSERT and RB-INSERT differ in four ways. • First, all instances of NIL in TREE-INSERT are replaced by T.nil. • Second, we set z.left and z.right to T. nil in lines 14–15 of RB-INSERT, in order to maintain the proper tree structure. • Third, we color z red in line 16. • Fourth, because coloring z.red may cause a violation of one of the red-black properties, we call RB-INSERT-FIXUP(T,z) in line 17 of RB-INSERT to restore the red-black properties
  • 17. Insertion • Case 1. z's uncle y is red • Case 2. z's uncle y is black and z is a right child • Case 3. z's uncle y is black and z is a left child
  • 21. Insertion Case3: z's uncle y is black and z is a left childCase2: z's uncle y is black and z is a right child
  • 22. Insertion RB-INSERT-FIXUP(T, z) 1. while z.p.color == RED 2. if z.p == z.p.p.left 3. then y ← z.p.p.right 4. if y.color== RED 5. then z.p.color← BLACK //Case 1 6. y.color ← BLACK //Case 1 7. z.p.p.color← RED //Case 1 8. z ← z.p.p // Case 1 9. else if z = z.p.right 10. then z ← z.p //Case 2 11. LEFT-ROTATE(T, z) //Case 2 12. z.p .color← BLACK //Case 3 13. z.p .p.color← RED //Case 3 14. RIGHT-ROTATE(T, z.p .p) // Case 3 15. else .same as then clause with "right" an= "left" exchange=) 16. T.root.color← BLACK
  • 23. Insertion • To understand how RB-INSERT-FIXUP works, we shall break our examination of the code into three major steps. • First, we shall determine what violations of the red-black properties are introduced in RB-INSERT when node z is inserted and colored red. • Second, we shall examine the overall goal of the while loop in lines 1–15. • Finally, we shall explore each of the three cases within the while loop’s body and see how they accomplish the goal.
  • 24. Insertion • The while loop in lines 1–15 maintains the following three-part invariant. • At the start of each iteration of the loop, a) Node z is red. b) If z.p is the root, then z.p is black. c) If there is a violation of the red-black properties , there is at most one violation, and it is of either property 2 or property 4. If there is a violation of property 2, it occurs because z is the root and is red. If there is a violation of property 4, it occurs because both z and z.p are red.
  • 25. Deletion • Like the other basic operations on an Red Black tree, deletion of a node takes time O(logn) • Deleting a node from a red-black tree is a bit more complicated than inserting a node. • The procedure for deleting a node from a red-black tree is based on the RB-DELETE procedure • First, we need to customize the TRANSPLANT subroutine that RB-DELETE calls so that it applies to a red-black tree.
  • 26. Deletion RB-TRANSPLANT(T.u.v) 1. if u.p == T.nil 2. T.root = v 3. elseif u == u.p.left 4. u.p.left = v 5. else u.p.right = v 6. v.p = u.p
  • 27. Deletion RB-DELETE (T,z) 1. y = z 2. y-original-color = y.color 3. if z.left = = T. nil 4. x = z. right 5. RB-TRANSPLANT (T, z, z. right) 6. elseif z. right = = T. nil 7. x = z. left 8. RB-TRANSPLANT(T, z, z. left) 9. else y = TREE-MINIMUM(z. right) 10. y-original-color = y. color 11. x = y. right 12. if y. p = = z 13. x. p = y
  • 28. Deletion 14. else RB-TRANSPLANT(T, y, y. right) 15. y. right = z. right 16. y. right. p = y 17. RB-TRANSPLANT(T, z, y) 18. y. left = z. left 19. y. left. p = y 20. y. color = z. color 21. if y-original-color == BLACK 22. RB-DELETE-FIXUP(T, x)
  • 29. Deletion Case 1: x's sibling w is red
  • 30. Deletion Case 2: x's sibling w is black, and both of w's children are black
  • 31. Deletion Case 3: x's sibling w is black, w's left child is red, and w's right child is black
  • 32. Deletion Case 4: x's sibling w is black, and w's right child is red
  • 33. Deletion RB-DELETE-FIXUP(T, x) 1. while x !=T.root an= x. color == BLACK 2. if x == x. p. left 3. w = x. p. right 4. if w. color = = RED 5. w. color = BLACK //case 1 6. x. p. color = RED //case 1 7. LEFT-ROTATE(T, x. p) //case 1 8. w = x. p. right //case 1 9. if w. left. color == BLACK and w. right. color = = BLACK 10. w. color = RED //case 2 11. x = x. p //case 2
  • 34. Deletion 12. else if w. right. color == BLACK 13. w. left. color = BLACK //case 3 14. w. color = RED //case 3 15. RIGHT-ROTATE(T, w) //case 3 16. w = x. p. right //case 3 17. w. color = x. p. color //case 4 18. x. p. color = BLACK //case 4 19. w. right. color = BLACK //case 4 20. LEFT-ROTATE(T, x. p) //case 4 21. x = T. root //case 4 22. else (same as then clause with “right” and “left” exchanged) 23. x. color = BLACK