SlideShare a Scribd company logo
1 of 63
RED BLACK
By
Samrin Ahmed Riya
Sanzida Akter
 Node based binary search tree
 Automatically balance it’s height in the face of arbitrary item
insertions and deletions
Fig : Balanced Tree
 A special kind of binary search tree
 Self balancing tree
 Height of right sub tree ˞˞ height of left sub tree ≤ 1
Georgy Adelson-Velsky and Evgenii Landis' tree
Named after the inventors (1962)
YES
Each left sub-tree has
height 1 greater than
each right sub-tree
NO
Left sub-tree has height 3,
but right sub-tree has height 1
 Insertion
 Deletion
 Traversal
 Searching
 It is performed as in binary search trees.
 For insertions, one rotation is sufficient.
 Sometimes it needs two rotations.
(0,0)1
Insert 1Elements :
1 2 3 6 15 -2 -5 -8
(0,0)2
(0,1)1
Insert 2Elements :
1 2 3 6 15 -2 -5 -8
Rotation needed 
(0,0)3
(0,1)2
(0,2)1
Insert 3Elements :
1 2 3 6 15 -2 -5 -8
1 (0,0)3
(1,1)2
Insert 3
(0,0)
Elements :
1 2 3 6 15 -2 -5 -8
1 (0,1)3
(1,2)2
Insert 6
(0,0)
(0,0)6
Elements :
1 2 3 6 15 -2 -5 -8
1 (0,2)3
(1,3)2
Insert 15
(0,0)
(0,1)6
(0,0)15
Rotation needed 
Elements :
1 2 3 6 15 -2 -5 -8
1 (1,1)6
(1,2)2
Insert 15
(0,0)
(0,0)153 (0,0)
Elements :
1 2 3 6 15 -2 -5 -8
1 (1,1)6
(2,2)2
Insert -2
(1,0)
(0,0)153 (0,0)-2 (1,0)
Elements :
1 2 3 6 15 -2 -5 -8
1 (1,1)6
(3,2)2
Insert -5
(2,0)
(0,0)153 (0,0)-2 (1,0)
-5 (0,0)
Rotation needed 
Elements :
1 2 3 6 15 -2 -5 -8
-2 (1,1)6
(2,2)2
Insert -5
(1,1)
(0,0)1 3
(0,0)
-5 (0,0)
(0,0)
(0,0)15
Elements :
1 2 3 6 15 -2 -5 -8
-2 (1,1)6
(3,2)2
Insert -8
(2,1)
(0,0)1 3
(0,0)
-5 (1,0)
(0,0)
(0,0)15
-8 (0,0)
Elements :
1 2 3 6 15 -2 -5 -8
 Deletion can make the tree unbalanced
 One rotation is needed for rebalancing
 Sometimes it needs two rotations
 LeftRotationAVL (x: BinTree) {
x := ( x. rightChild .key ,
(x.key , x. leftChild , x. rightChild . leftChild ) ,
x. rightChild . rightChild );
}
 RightRotation (x: BinTree) {
x := ( x. leftChild .key ,
x. leftChild . leftChild ,
(x.key , x. leftChild . rightChild , x. rightChild ) );
}
 RightLeftRotation (x: BinTree) {
x := ( x. rightChild . leftChild .key ,
( x.key , x. leftChild , x. rightChild . leftChild . leftChild ) ,
( x. rightChild .key , x. rightChild . leftChild . rightChild , x.
rightChild . rightChild ) ); }
 LeftRightRotation(x: BinTree) {
x := ( x. leftChild . rightChild .key ,
( x. leftChild .key , x. leftChild . leftChild ,
x. leftChild . rightChild . leftChild ) , ( x.key , x. leftChild .
rightChild . rightChild , x. rightChild ) ); }
 Maintains preorder, inorder and postorder traversal
 Depends on the height of the tree
Preorder Traversal
void preorder(node *t) {
if (t != NULL) {
printf(“%d ”, t->element);
preorder(t->leftChild);
preorder(t->rightChild);
}
}
Inorder Traversal
void inorder(node *t) {
if (t != NULL) {
inorder(t->leftChild);
printf(“%d ”, t->element);
inorder(t->rightChild);
}
}
Postorder Traversal
void postorder(node *t) {
if (t != NULL) {
postorder(t->leftChild); /* L */
postorder(t->rightChild); /* R */
printf(“%d ”, t->element); /* V */
}
}
 Similar to normal unbalanced binary search tree.
 Successful searches are limited by the height of the tree.
 Unsuccessful searching time is very close to the height of the
tree.
 Used in many search applications where data is constantly
entering/leaving.
 To security concerns and to parallel code.
 Creating new types of data structures.
• 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.
• 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.
Average
Space O(n)
Search
O(log2 n)
Traversal O(n)
Insertion
O(log2 n)
Deletion
O(log2 n)
• Basic operation for changing tree structure is
called rotation:
x
y
y
x
• 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
• Rotate left about 9:
12
5 9
7
8
11
• Rotate left about 9:
5 12
7
9
118
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.
• 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)
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
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
● 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
• 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)
Insert 65
47
7132
93
Insert 65
47
7132
65 93
Insert 65
47
7132
65 93
Insert 82
82
Insert 65 47
7132
65 93
Insert 82
82
Insert 65
47
7132
65 93
Insert 82
65
71
93
change nodes’ colors
9365
71
82
Insert 65
47
32
Insert 82
Insert 87
87
9365
71
82
Insert 65
47
32
Insert 82
Insert 87
87
9365
71
87
Insert 65
47
32
Insert 82
Insert 87
82
9365
87
Insert 65
47
32
Insert 82
Insert 87
82
71
87
93
change nodes’ colors
87
93
65
Insert 65
47
32
Insert 82
Insert 87
82
71
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;
}
• If n has no children, we only have to remove n from the tree.
• If n has a single child, we remove n and connect its parent to its child.
• If n has two children, we need to :
• Find the smallest node that is larger than n, call it m.
• Remove m from the tree and Replace the value of n with m.
• Then restores the red-black tree properties.
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);
}
• Searching a node from a red-black tree doesn’t require more than the
use of the BST procedure, which takes O(log n) time.
 All operations work in time O(height)
 hence, all operations work in time O(log n)! – much
more efficient than linked list or arrays implementation
of sorted list!
• Completely Fair Scheduler in Linux Kernel.
• Computational Geometry Data structures.
• 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.
For small data :
• Insert: RB tree will be faster because on average it uses less rotation.
• Lookup: AVL tree is faster, because it has less depth.
• Delete: RB tree is faster for it’s runtime.
For large data :
• Insert: AVL tree is faster, because it maintains O(log n) which is better than RB
tree.
• 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.
Balanced Tree(AVL Tree,Red Black Tree)

More Related Content

What's hot (20)

Red black tree
Red black treeRed black tree
Red black tree
 
Red black 1
Red black 1Red black 1
Red black 1
 
Red black trees1109
Red black trees1109Red black trees1109
Red black trees1109
 
Red black tree
Red black treeRed black tree
Red black tree
 
Red black trees presentation
Red black trees presentationRed black trees presentation
Red black trees presentation
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
 
Lec14
Lec14Lec14
Lec14
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Avl trees
Avl treesAvl trees
Avl trees
 
lecture 14
lecture 14lecture 14
lecture 14
 
Data Structure: TREES
Data Structure: TREESData Structure: TREES
Data Structure: TREES
 
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
 
16 rbtrees
16 rbtrees16 rbtrees
16 rbtrees
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 

Similar to Balanced Tree(AVL Tree,Red Black Tree)

Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAdityaK92
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structureAnusruti Mitra
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.pptplagcheck
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docxfredharris32
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptxRedHeart11
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
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.pptSheba41
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologyKamranAli649587
 

Similar to Balanced Tree(AVL Tree,Red Black Tree) (20)

Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
UNIT II.ppt
UNIT II.pptUNIT II.ppt
UNIT II.ppt
 
BST.pdf
BST.pdfBST.pdf
BST.pdf
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.ppt
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
Trees
TreesTrees
Trees
 
Red black tree
Red black treeRed black tree
Red black tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
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
 
rbtrees.ppt
rbtrees.pptrbtrees.ppt
rbtrees.ppt
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
C12 bst
C12 bstC12 bst
C12 bst
 
C12 bst
C12 bstC12 bst
C12 bst
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
TREES.pptx
TREES.pptxTREES.pptx
TREES.pptx
 
lecture14.ppt
lecture14.pptlecture14.ppt
lecture14.ppt
 
Red black trees
Red black treesRed black trees
Red black trees
 

More from B.Sc in CSE, United International University - UIU, Dhaka (7)

Electronics project
Electronics projectElectronics project
Electronics project
 
Leisure Life E-Commerce Bookstore
Leisure Life E-Commerce BookstoreLeisure Life E-Commerce Bookstore
Leisure Life E-Commerce Bookstore
 
Project Management Tool & Technique of Online Bookstore
Project Management Tool & Technique of Online BookstoreProject Management Tool & Technique of Online Bookstore
Project Management Tool & Technique of Online Bookstore
 
Sudoku
SudokuSudoku
Sudoku
 
Tree of Data Structure
Tree of Data StructureTree of Data Structure
Tree of Data Structure
 
Karnaugh Graph or K-Map
Karnaugh Graph or K-MapKarnaugh Graph or K-Map
Karnaugh Graph or K-Map
 
Bermuda Triangle
Bermuda TriangleBermuda Triangle
Bermuda Triangle
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

Balanced Tree(AVL Tree,Red Black Tree)

  • 1. RED BLACK By Samrin Ahmed Riya Sanzida Akter
  • 2.  Node based binary search tree  Automatically balance it’s height in the face of arbitrary item insertions and deletions Fig : Balanced Tree
  • 3.
  • 4.  A special kind of binary search tree  Self balancing tree  Height of right sub tree ˞˞ height of left sub tree ≤ 1 Georgy Adelson-Velsky and Evgenii Landis' tree Named after the inventors (1962)
  • 5.
  • 6. YES Each left sub-tree has height 1 greater than each right sub-tree NO Left sub-tree has height 3, but right sub-tree has height 1
  • 7.  Insertion  Deletion  Traversal  Searching
  • 8.
  • 9.  It is performed as in binary search trees.  For insertions, one rotation is sufficient.  Sometimes it needs two rotations.
  • 10. (0,0)1 Insert 1Elements : 1 2 3 6 15 -2 -5 -8
  • 12. Rotation needed  (0,0)3 (0,1)2 (0,2)1 Insert 3Elements : 1 2 3 6 15 -2 -5 -8
  • 15. 1 (0,2)3 (1,3)2 Insert 15 (0,0) (0,1)6 (0,0)15 Rotation needed  Elements : 1 2 3 6 15 -2 -5 -8
  • 16. 1 (1,1)6 (1,2)2 Insert 15 (0,0) (0,0)153 (0,0) Elements : 1 2 3 6 15 -2 -5 -8
  • 17. 1 (1,1)6 (2,2)2 Insert -2 (1,0) (0,0)153 (0,0)-2 (1,0) Elements : 1 2 3 6 15 -2 -5 -8
  • 18. 1 (1,1)6 (3,2)2 Insert -5 (2,0) (0,0)153 (0,0)-2 (1,0) -5 (0,0) Rotation needed  Elements : 1 2 3 6 15 -2 -5 -8
  • 19. -2 (1,1)6 (2,2)2 Insert -5 (1,1) (0,0)1 3 (0,0) -5 (0,0) (0,0) (0,0)15 Elements : 1 2 3 6 15 -2 -5 -8
  • 20. -2 (1,1)6 (3,2)2 Insert -8 (2,1) (0,0)1 3 (0,0) -5 (1,0) (0,0) (0,0)15 -8 (0,0) Elements : 1 2 3 6 15 -2 -5 -8
  • 21.  Deletion can make the tree unbalanced  One rotation is needed for rebalancing  Sometimes it needs two rotations
  • 22.  LeftRotationAVL (x: BinTree) { x := ( x. rightChild .key , (x.key , x. leftChild , x. rightChild . leftChild ) , x. rightChild . rightChild ); }  RightRotation (x: BinTree) { x := ( x. leftChild .key , x. leftChild . leftChild , (x.key , x. leftChild . rightChild , x. rightChild ) ); }
  • 23.  RightLeftRotation (x: BinTree) { x := ( x. rightChild . leftChild .key , ( x.key , x. leftChild , x. rightChild . leftChild . leftChild ) , ( x. rightChild .key , x. rightChild . leftChild . rightChild , x. rightChild . rightChild ) ); }  LeftRightRotation(x: BinTree) { x := ( x. leftChild . rightChild .key , ( x. leftChild .key , x. leftChild . leftChild , x. leftChild . rightChild . leftChild ) , ( x.key , x. leftChild . rightChild . rightChild , x. rightChild ) ); }
  • 24.  Maintains preorder, inorder and postorder traversal  Depends on the height of the tree
  • 25. Preorder Traversal void preorder(node *t) { if (t != NULL) { printf(“%d ”, t->element); preorder(t->leftChild); preorder(t->rightChild); } }
  • 26. Inorder Traversal void inorder(node *t) { if (t != NULL) { inorder(t->leftChild); printf(“%d ”, t->element); inorder(t->rightChild); } }
  • 27. Postorder Traversal void postorder(node *t) { if (t != NULL) { postorder(t->leftChild); /* L */ postorder(t->rightChild); /* R */ printf(“%d ”, t->element); /* V */ } }
  • 28.  Similar to normal unbalanced binary search tree.  Successful searches are limited by the height of the tree.  Unsuccessful searching time is very close to the height of the tree.
  • 29.
  • 30.  Used in many search applications where data is constantly entering/leaving.  To security concerns and to parallel code.  Creating new types of data structures.
  • 31.
  • 32. • 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.
  • 33.
  • 34. • 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.
  • 35. Average Space O(n) Search O(log2 n) Traversal O(n) Insertion O(log2 n) Deletion O(log2 n)
  • 36. • Basic operation for changing tree structure is called rotation:
  • 37. x y y x • 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
  • 38. • Rotate left about 9: 12 5 9 7 8 11
  • 39. • Rotate left about 9: 5 12 7 9 118
  • 40. 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.
  • 41. • 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)
  • 42. 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
  • 43. 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
  • 44. ● 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
  • 45. • 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)
  • 49. 82 Insert 65 47 7132 65 93 Insert 82
  • 50. 82 Insert 65 47 7132 65 93 Insert 82 65 71 93 change nodes’ colors
  • 54. 9365 87 Insert 65 47 32 Insert 82 Insert 87 82 71 87 93 change nodes’ colors
  • 56. 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; }
  • 57. • If n has no children, we only have to remove n from the tree. • If n has a single child, we remove n and connect its parent to its child. • If n has two children, we need to : • Find the smallest node that is larger than n, call it m. • Remove m from the tree and Replace the value of n with m. • Then restores the red-black tree properties.
  • 58. 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); }
  • 59. • Searching a node from a red-black tree doesn’t require more than the use of the BST procedure, which takes O(log n) time.
  • 60.  All operations work in time O(height)  hence, all operations work in time O(log n)! – much more efficient than linked list or arrays implementation of sorted list!
  • 61. • Completely Fair Scheduler in Linux Kernel. • Computational Geometry Data structures. • 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.
  • 62. For small data : • Insert: RB tree will be faster because on average it uses less rotation. • Lookup: AVL tree is faster, because it has less depth. • Delete: RB tree is faster for it’s runtime. For large data : • Insert: AVL tree is faster, because it maintains O(log n) which is better than RB tree. • 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.