SlideShare a Scribd company logo
1 of 23
Red-black Trees



            Author:
            Varun Mahajan
            <varunmahajan06@gmail.com>
Contents
 ●
     Dynamic sets
       ●
           Operations on Dynamic sets

 ●
     Binary trees: Basic terminology

 ●
     Binary search trees
       ●
           TREE_SEARCH
       ●
           TREE_INSERT
       ●
           Operations' running time: O(h)

 ●
     Red-black trees
       ●
           Red-black properties
       ●
           Height: O(lg n)
       ●
           Queries: O(lg n)
       ●
           Rotations: O(1)
       ●
           RB-INSERT: O(lg n)
Dynamic sets
 Set: A collection of objects of a particular kind

 The Sets manipulated by algorithms can grow, shrink, or otherwise change
 over time. Such sets are called Dynamic Sets

 In a typical implementation of a dynamic set, each element is represented by
 an object whose fields can be examined and manipulated if we have a pointer
 to the object

 Object fields:
    ●
      Identifying Key field
    ●
      Satellite data
Operations on Dynamic sets
 Two categories:
 ●
   Queries
 ●
   Modifying Operations

 SEARCH(S,k): A query that, given a set S and a key value k, returns a
 pointer x to an element in S such that key[x] = k, or NIL if no such element
 belongs to S

 INSERT(S,x): A modifying operation that augments the set S with the
 element pointed to by x. We usually assume that any fields in element x
 needed by the set implementation have already been initialized

 DELETE(S,x): A modifying operation that, given a pointer x to an element in
 the set S, removes x from S. (Note that this operation uses a pointer to an
 element x, not a key value.)

 MINIMUM(S): A query on a totally ordered set S that returns a pointer to
 the element of S with the smallest key
Operations on Dynamic sets
 MAXIMUM(S): A query on a totally ordered set S that returns a pointer to
 the element of S with the largest key

 SUCCESSOR(S,x): A query that, given an element x whose key is from a
 totally ordered set S, returns a pointer to the next larger element in S, or NIL
 if x is the maximum element

 PREDESESSOR(S,x): A query that, given an element x whose key is from a
 totally ordered set S, returns a pointer to the next smaller element in S, or
 NIL if x is the minimum element




 Totally ordered set: For any two elements a and b in the set, exactly one of the
 following must hold: a < b, a = b, or a > b
Binary trees
 Binary trees are defined recursively. A binary tree T is a structure defined on
 a finite set of nodes that either

     ●
         contains no nodes, or
     ●
         is composed of three disjoint sets of nodes: a root node, a binary tree
         called its left subtree, and a binary tree called its right subtree

 The binary tree that contains no nodes is called the empty tree or null tree,
 sometimes denoted NIL

 If the left subtree is nonempty, its root is called the left child of the root of
 the entire tree

 Likewise, the root of a nonnull right subtree is the right child of the root of
 the entire tree

 A node with no children is an external node or leaf

 A nonleaf node is an internal node
Binary trees
 If n1, n2, . . . , nk is a sequence of nodes in a tree such that ni is the parent
 of ni+1 for 1 ≤ i < k, then this sequence is called a path from node n1 to
 node nk.

 The length of a path is one less than the number of nodes in the path

 The height of a node in a tree is the length of a longest path from the node
 to a leaf

 The height of a tree is the height of the root

 The depth of a node is the length of the unique path from the root to that
 node
Binary Search trees




 The keys in a binary search tree are always stored in such a way as to
 satisfy the binary-search-tree property:

    ●
        Let x be a node in a binary search tree. If y is a node in the left subtree
        of x, then key[y] ≤ key[x]. If y is a node in the right subtree of x, then
        key[x] ≤ key[y]
TREE-SEARCH
 T R E E -S E A R C H (T, k )

  if T = N I L of k = key[T ]
       return T
  els e if k < key[T ]
       return T R E E -S E A R C H (left[T ], k )
  els e
       return T R E E -S E A R C H (rig ht[T ], k )

 TREE-SEARCH runs in O(h) time on a tree of height h




                                                      (a) A binary search tree on 6 nodes
                                                      with height 2. (b) A less efficient
                                                      binary search tree with height 4 that
                                                      contains the same keys
TREE-INSERT
 T R E E -I N S E R T (T, x )

  if T = N I L
       T = x
  return
  els e if key[x ] < key[T ]
       return T R E E -I N S E R T (left[T ], x )
  els e
       return T R E E -I N S E R T (rig ht[T ], x )

 TREE-INSERT runs in O(h) time on a tree of height h




                                                      Inserting an item with key 13 into a binary
                                                      search tree. Lightly shaded nodes indicate the
                                                      path from the root down to the position where
                                                      the item is inserted. The dashed line indicates
                                                      the link in the tree that is added to insert the
                                                      item
Binary Search trees Operations: Running time
  The worst-case running time for most search-tree operations is
  proportional to the height of the tree

  Queries:
     ●
       TREE-SEARCH(S,k):        O(h)
     ●
       TREE-MINIMUM(S):         O(h)
     ●
       TREE-MAXIMUM(S):         O(h)
     ●
       TREE-SUCCESSOR(S,x):     O(h)
     ●
       TREE-PREDECESSOR(S,x):   O(h)

  Modifying operations:
     ●
       TREE-INSERT(S,x):        O(h)
     ●
       TREE-DELETE(S,x):        O(h)
Red-black trees
 Red-black trees are binary search trees that are "balanced" in order to
 guarantee that basic dynamic-set operations take O(lg n) time in the
 worst case (height of the tree: O(lg n) where n is the no of nodes)

 A red-black tree is a binary search tree with one extra bit of storage per node:
 its color, which can be either RED or BLACK. By constraining the way
 nodes can be colored on any 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
Red-black properties
 Binary search tree is a red-black tree if it satisfies the following red-black
 properties:
     ●
       Every node is either red or black
     ●
       The root is black
     ●
       Every leaf (NIL) is black
     ●
       If a node is red, then both its children are black
     ●
       For each node, all paths from the node to descendant leaves contain the same
       number of black nodes

 The number of black nodes on any path from, but not including, a node x down to a leaf
 is called the black-height of the node, denoted as bh(x)

 black-height of a red-black tree is the black-height of its root
Height O(lg n)
 A red-black tree with n internal nodes has height at most 2 lg(n + 1)
 i.e. O(lg n)

     ●
         A subtree rooted at x contains internal nodes >= 2^bh(x) -1

          ●
              For leaf: bh(leaf) = 0 => internal nodes = 2^0 - 1 = 0 (TRUE)
          ●
              For internal node x with two children:
                ●
                    Each child has black height bh(x) or bh(x) -1, depending on whether its color is red or
                    black, respectively
                ●
                    Subtree rooted at x: internal nodes >= (2^ (bh(x) – 1) -1) + (2^ (bh(x) – 1) -1) + 1 =
                    2^bh(x) -1 (TRUE)
          ●
              Claim is proved by induction

     ●
         The black-height of the root must be at least h/2 by property 4 (h is
         height of tree)

          ●
              n >= 2^bh(root) - 1
          ●
              n >= 2^(h/2) – 1
          ●
              lg(n +1) >= h/2
          ●
              h <= 2 lg(n+1)

 An immediate consequence of this lemma is that the dynamic-set operations
 SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, and PREDECESSOR can be
 implemented in O(lg n) time on red-black trees, since they can be made to run
 in O(h) time on a search tree of height h and any red-black tree on n nodes is a
 search tree with height O(lg n)
Rotations
• A local operation in a
search tree which changes
the pointer structure and
preserves    the     binary-
search-tree property

• Both LEFT-ROTATE and
RIGHT-ROTATE run in O(1)
time. Only pointers are
changed by a rotation; all
other fields in a node
remain the same
RB-INSERT
R B -I N S E R T (T, z)

    T R E E -I N S E R T (T, z)
    c o lo r[z] = R E D
    R B -I N S E R T-FI X U P (T, z)
RB-INSERT-FIXUP: Case 1
R B -I N S E R T-FI X U P (T, z)
RB-INSERT-FIXUP: Case 2,3
R B -I N S E R T-FI X U P (T, z)
RB-INSERT-FIXUP: Example
RB-INSERT: Running time
R B -I N S E R T (T, z): O (lg n)

       T R E E -I N S E R T (T, z)              O (lg n)
       c o lo r[z] = R E D                      O (1)
       R B -I N S E R T-FI X U P (T, z)         O (lg n)

 R B -I N S E R T-FI X U P (T, z): O (lg n)
   ●
        Case 1: The pointer z moves two levels up the tree. Maximum times this can happen
        (when case 1 is repeated) is O(lg n)
   ●
        Case 2,3: At the maximum two rotations are done




The running time of RB-DELETE(T, z) is also O(lg n)
Exercise
 Study:

   ●
       TREE-DELETE, TREE-SUCCESSOR, TREE_PREDECESSOR
   ●
       RB-DELETE
   ●
       Linux kernel implementation of Red-black tree:
         ●
           ../include/linux/rbtree.h
         ●
           ../lib/rbtree.c
References
 ●
  Introduction to Algorithms, Second Edition, Thomas H. Cormen, Charles E. Leiserson, Ronald
 L. Rivest, Clifford Stein; The MIT Press

 ●
     http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-alg

 ●
     http://lwn.net/Articles/184495/
END...

More Related Content

What's hot

Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structureVrushali Dhanokar
 
Red black tree
Red black treeRed black tree
Red black treeuos lahore
 
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kamber
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; KamberChapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kamber
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kambererror007
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysisajmalcs
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
Data Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessingData Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessing
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessingSalah Amean
 
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Binary search trees
Binary search treesBinary search trees
Binary search treesDwight Sabio
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]DEEPIKA T
 
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 TreeManishPrajapati78
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Hasanain Alshadoodee
 

What's hot (20)

Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Apriori algorithm
Apriori algorithmApriori algorithm
Apriori algorithm
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kamber
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; KamberChapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kamber
Chapter - 6 Data Mining Concepts and Techniques 2nd Ed slides Han &amp; Kamber
 
Amortized analysis
Amortized analysisAmortized analysis
Amortized analysis
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
Data Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessingData Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessing
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
 
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDYDATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
DATA STRUCTURES AND ALGORITHMS UNIT-3 TREES PREPARED BY M V BRAHMANANDA REDDY
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
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
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Red Black Tree Insertion & Deletion
Red Black Tree Insertion & DeletionRed Black Tree Insertion & Deletion
Red Black Tree Insertion & Deletion
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
BINARY SEARCH TREE
BINARY SEARCH TREE BINARY SEARCH TREE
BINARY SEARCH TREE
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking 
 

Viewers also liked (8)

Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Red black trees1109
Red black trees1109Red black trees1109
Red black trees1109
 
10 Red-Black Trees
10 Red-Black Trees10 Red-Black Trees
10 Red-Black Trees
 
Red black trees presentation
Red black trees presentationRed black trees presentation
Red black trees presentation
 
Red Black Tree
Red Black TreeRed Black Tree
Red Black Tree
 
Insertion in RED BLACK TREE
Insertion in RED BLACK TREEInsertion in RED BLACK TREE
Insertion in RED BLACK TREE
 
Intro to Graphing Data Powerpoint-7th and 8th Grade
Intro to Graphing Data Powerpoint-7th and 8th GradeIntro to Graphing Data Powerpoint-7th and 8th Grade
Intro to Graphing Data Powerpoint-7th and 8th Grade
 
Introduction to graph class 8
Introduction to graph class 8Introduction to graph class 8
Introduction to graph class 8
 

Similar to Red Black Trees

lecture 13
lecture 13lecture 13
lecture 13sajinsc
 
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 treeszukun
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAdityaK92
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.pptplagcheck
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
Data structures final lecture 1
Data structures final  lecture 1Data structures final  lecture 1
Data structures final lecture 1Nazir Ahmed
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.pptSuneel61
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfssuser034ce1
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfssuser034ce1
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overviewElifTech
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptxRedHeart11
 

Similar to Red Black Trees (20)

lecture 13
lecture 13lecture 13
lecture 13
 
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
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
15-btrees.ppt
15-btrees.ppt15-btrees.ppt
15-btrees.ppt
 
Review session2
Review session2Review session2
Review session2
 
UNIT II.ppt
UNIT II.pptUNIT II.ppt
UNIT II.ppt
 
7.tree
7.tree7.tree
7.tree
 
Data structures final lecture 1
Data structures final  lecture 1Data structures final  lecture 1
Data structures final lecture 1
 
16 rbtrees
16 rbtrees16 rbtrees
16 rbtrees
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
Trees
TreesTrees
Trees
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
 
tree.ppt
tree.ppttree.ppt
tree.ppt
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 

More from Varun Mahajan

I2C Bus (Inter-Integrated Circuit)
I2C Bus (Inter-Integrated Circuit)I2C Bus (Inter-Integrated Circuit)
I2C Bus (Inter-Integrated Circuit)Varun Mahajan
 
I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24Varun Mahajan
 
Hibernation in Linux 2.6.29
Hibernation in Linux 2.6.29Hibernation in Linux 2.6.29
Hibernation in Linux 2.6.29Varun Mahajan
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxVarun Mahajan
 
Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Varun Mahajan
 
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSI
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSIIntroduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSI
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSIVarun Mahajan
 

More from Varun Mahajan (6)

I2C Bus (Inter-Integrated Circuit)
I2C Bus (Inter-Integrated Circuit)I2C Bus (Inter-Integrated Circuit)
I2C Bus (Inter-Integrated Circuit)
 
I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24
 
Hibernation in Linux 2.6.29
Hibernation in Linux 2.6.29Hibernation in Linux 2.6.29
Hibernation in Linux 2.6.29
 
Process' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/LinuxProcess' Virtual Address Space in GNU/Linux
Process' Virtual Address Space in GNU/Linux
 
Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)
 
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSI
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSIIntroduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSI
Introduction to GNU/Linux, Free Software, Open Source Software, FSF, FSM, OSI
 

Recently uploaded

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
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
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
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🔝
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 

Red Black Trees

  • 1. Red-black Trees Author: Varun Mahajan <varunmahajan06@gmail.com>
  • 2. Contents ● Dynamic sets ● Operations on Dynamic sets ● Binary trees: Basic terminology ● Binary search trees ● TREE_SEARCH ● TREE_INSERT ● Operations' running time: O(h) ● Red-black trees ● Red-black properties ● Height: O(lg n) ● Queries: O(lg n) ● Rotations: O(1) ● RB-INSERT: O(lg n)
  • 3. Dynamic sets Set: A collection of objects of a particular kind The Sets manipulated by algorithms can grow, shrink, or otherwise change over time. Such sets are called Dynamic Sets In a typical implementation of a dynamic set, each element is represented by an object whose fields can be examined and manipulated if we have a pointer to the object Object fields: ● Identifying Key field ● Satellite data
  • 4. Operations on Dynamic sets Two categories: ● Queries ● Modifying Operations SEARCH(S,k): A query that, given a set S and a key value k, returns a pointer x to an element in S such that key[x] = k, or NIL if no such element belongs to S INSERT(S,x): A modifying operation that augments the set S with the element pointed to by x. We usually assume that any fields in element x needed by the set implementation have already been initialized DELETE(S,x): A modifying operation that, given a pointer x to an element in the set S, removes x from S. (Note that this operation uses a pointer to an element x, not a key value.) MINIMUM(S): A query on a totally ordered set S that returns a pointer to the element of S with the smallest key
  • 5. Operations on Dynamic sets MAXIMUM(S): A query on a totally ordered set S that returns a pointer to the element of S with the largest key SUCCESSOR(S,x): A query that, given an element x whose key is from a totally ordered set S, returns a pointer to the next larger element in S, or NIL if x is the maximum element PREDESESSOR(S,x): A query that, given an element x whose key is from a totally ordered set S, returns a pointer to the next smaller element in S, or NIL if x is the minimum element Totally ordered set: For any two elements a and b in the set, exactly one of the following must hold: a < b, a = b, or a > b
  • 6. Binary trees Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either ● contains no nodes, or ● is composed of three disjoint sets of nodes: a root node, a binary tree called its left subtree, and a binary tree called its right subtree The binary tree that contains no nodes is called the empty tree or null tree, sometimes denoted NIL If the left subtree is nonempty, its root is called the left child of the root of the entire tree Likewise, the root of a nonnull right subtree is the right child of the root of the entire tree A node with no children is an external node or leaf A nonleaf node is an internal node
  • 7. Binary trees If n1, n2, . . . , nk is a sequence of nodes in a tree such that ni is the parent of ni+1 for 1 ≤ i < k, then this sequence is called a path from node n1 to node nk. The length of a path is one less than the number of nodes in the path The height of a node in a tree is the length of a longest path from the node to a leaf The height of a tree is the height of the root The depth of a node is the length of the unique path from the root to that node
  • 8. Binary Search trees The keys in a binary search tree are always stored in such a way as to satisfy the binary-search-tree property: ● Let x be a node in a binary search tree. If y is a node in the left subtree of x, then key[y] ≤ key[x]. If y is a node in the right subtree of x, then key[x] ≤ key[y]
  • 9. TREE-SEARCH T R E E -S E A R C H (T, k ) if T = N I L of k = key[T ] return T els e if k < key[T ] return T R E E -S E A R C H (left[T ], k ) els e return T R E E -S E A R C H (rig ht[T ], k ) TREE-SEARCH runs in O(h) time on a tree of height h (a) A binary search tree on 6 nodes with height 2. (b) A less efficient binary search tree with height 4 that contains the same keys
  • 10. TREE-INSERT T R E E -I N S E R T (T, x ) if T = N I L T = x return els e if key[x ] < key[T ] return T R E E -I N S E R T (left[T ], x ) els e return T R E E -I N S E R T (rig ht[T ], x ) TREE-INSERT runs in O(h) time on a tree of height h Inserting an item with key 13 into a binary search tree. Lightly shaded nodes indicate the path from the root down to the position where the item is inserted. The dashed line indicates the link in the tree that is added to insert the item
  • 11. Binary Search trees Operations: Running time The worst-case running time for most search-tree operations is proportional to the height of the tree Queries: ● TREE-SEARCH(S,k): O(h) ● TREE-MINIMUM(S): O(h) ● TREE-MAXIMUM(S): O(h) ● TREE-SUCCESSOR(S,x): O(h) ● TREE-PREDECESSOR(S,x): O(h) Modifying operations: ● TREE-INSERT(S,x): O(h) ● TREE-DELETE(S,x): O(h)
  • 12. Red-black trees Red-black trees are binary search trees that are "balanced" in order to guarantee that basic dynamic-set operations take O(lg n) time in the worst case (height of the tree: O(lg n) where n is the no of nodes) A red-black tree is a binary search tree with one extra bit of storage per node: its color, which can be either RED or BLACK. By constraining the way nodes can be colored on any 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
  • 13. Red-black properties Binary search tree is a red-black tree if it satisfies the following red-black properties: ● Every node is either red or black ● The root is black ● Every leaf (NIL) is black ● If a node is red, then both its children are black ● For each node, all paths from the node to descendant leaves contain the same number of black nodes The number of black nodes on any path from, but not including, a node x down to a leaf is called the black-height of the node, denoted as bh(x) black-height of a red-black tree is the black-height of its root
  • 14. Height O(lg n) A red-black tree with n internal nodes has height at most 2 lg(n + 1) i.e. O(lg n) ● A subtree rooted at x contains internal nodes >= 2^bh(x) -1 ● For leaf: bh(leaf) = 0 => internal nodes = 2^0 - 1 = 0 (TRUE) ● For internal node x with two children: ● Each child has black height bh(x) or bh(x) -1, depending on whether its color is red or black, respectively ● Subtree rooted at x: internal nodes >= (2^ (bh(x) – 1) -1) + (2^ (bh(x) – 1) -1) + 1 = 2^bh(x) -1 (TRUE) ● Claim is proved by induction ● The black-height of the root must be at least h/2 by property 4 (h is height of tree) ● n >= 2^bh(root) - 1 ● n >= 2^(h/2) – 1 ● lg(n +1) >= h/2 ● h <= 2 lg(n+1) An immediate consequence of this lemma is that the dynamic-set operations SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, and PREDECESSOR can be implemented in O(lg n) time on red-black trees, since they can be made to run in O(h) time on a search tree of height h and any red-black tree on n nodes is a search tree with height O(lg n)
  • 15. Rotations • A local operation in a search tree which changes the pointer structure and preserves the binary- search-tree property • Both LEFT-ROTATE and RIGHT-ROTATE run in O(1) time. Only pointers are changed by a rotation; all other fields in a node remain the same
  • 16. RB-INSERT R B -I N S E R T (T, z) T R E E -I N S E R T (T, z) c o lo r[z] = R E D R B -I N S E R T-FI X U P (T, z)
  • 17. RB-INSERT-FIXUP: Case 1 R B -I N S E R T-FI X U P (T, z)
  • 18. RB-INSERT-FIXUP: Case 2,3 R B -I N S E R T-FI X U P (T, z)
  • 20. RB-INSERT: Running time R B -I N S E R T (T, z): O (lg n) T R E E -I N S E R T (T, z) O (lg n) c o lo r[z] = R E D O (1) R B -I N S E R T-FI X U P (T, z) O (lg n) R B -I N S E R T-FI X U P (T, z): O (lg n) ● Case 1: The pointer z moves two levels up the tree. Maximum times this can happen (when case 1 is repeated) is O(lg n) ● Case 2,3: At the maximum two rotations are done The running time of RB-DELETE(T, z) is also O(lg n)
  • 21. Exercise Study: ● TREE-DELETE, TREE-SUCCESSOR, TREE_PREDECESSOR ● RB-DELETE ● Linux kernel implementation of Red-black tree: ● ../include/linux/rbtree.h ● ../lib/rbtree.c
  • 22. References ● Introduction to Algorithms, Second Edition, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein; The MIT Press ● http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-alg ● http://lwn.net/Articles/184495/