SlideShare une entreprise Scribd logo
1  sur  7
Télécharger pour lire hors ligne
Balanced Trees                                        Solution
• Binary search trees: if all levels filled, then   • Keep the trees height balanced (for every
  search, insertion and deletion are O(log N).        node, the difference in height between left
• However, performance may deteriorate to             and right subtrees at most 1)
  linear if nodes are inserted in order:            • Performance always logarithmic.
           10
                11
                      12




                     Example                          How to keep the tree balanced
Level 0                10
                                                    • Still need to insert preserving the order of
                7
Level 1                         13                    keys (otherwise search does not work)
Level 2
                                                    • Insert as the new items arrive (cannot wait
           6               12        15               till have all items)
Level 3                                             • So need to alter the tree as more items
                                14
                                                      arrive.




          Top down and bottom up
                                                                     Examples
                 insertion
• Top down insertion algorithms make                • Bottom up: AVL trees
  changes to the tree (necessary to keep the        • Top down: red-black trees
  tree balanced) as they search for the place to
  insert the item. They make one pass through
  the tree.                                         • Exposition (not in Shaffer): follows
• Bottom up: first insert the item, and then          M.A.Weiss, Data structures and problem
  work back through the tree making changes.          solving using Java, 2nd edition.
  Less efficient because make two passes
  through the tree.




                                                                                                     1
AVL Trees                              Non-example and example
• AVL (Adelson-Velskii & Landis) trees are         Not an AVL:                               AVL:
  binary search trees where nodes also have
                                                        X (2)                                 B
  additional information: the difference in
  depth between their left and right subtrees
  (balance factor). First example of balanced       A           B (1)                    X        D
  trees.
                                                        C               D            A       C        E
• It is represented as a number equal to the
  depth of the right subtree minus the depth of                                 E
  the left subtree. Can be 0,1 or -1.




        Depth of an AVL tree                                Insertion in AVL Trees
• Calculating the maximal depth of an AVL          • Insert new leaf node, as for ordinary binary
  tree is more difficult than calculating it for     search tree.
  prefectly balanced or complete binary trees.     • Then work back up from new leaf to root,
• An (almost complete) calculation is given in       checking if any height imbalance has been
  Weiss’s book (Ch.19.4.1). It gives                 introduced (computing new balance
  approximately 1.44 log(N+2) - 1.328 as the         factors).
  upper bound on the height, so it’s O(log N).     • Perform rotation to correct height imbalance
• An average depth of a node in an AVL tree          (which rotation depends on the balance
  is not established analytically yet.               factor).




                   Rotations                                          Right rotation
• The restructuring is done by performing a        • Right rotation around X (tree is heavier on
  rotation.                                          the left):
• A rotation is performed around some node                                  X (-2)
  X. It can be
  • single right rotation,                                        A
  • single left rotation or
                                                            B               C
  • a double rotation.




                                                                                                          2
Right rotation                                      Right rotation
• Right rotation around X:                      • X moves down and to the right, into the
                                                  position of its right child;
                     X (-2)            A
                                                • X's right subtree is unchanged.
                                                • X's left child A moves up to take X's place.
               A                   B       X      X is now A's new right child.
                                                • This leaves the old right child of A
       B            C                  C          unaccounted for. Since it comes from the
                                                  left of X, it is less than X. So it becomes X's
                                                  new left child.




                   Left rotation                                       Left rotation
• The tree is heavier on the right:             • Left rotation around X:
           X (2)                                      X (2)                                  B


       A            B                            A            B                         X        D

           C             D                           C                 D            A        C       E

                               E                                           E




               Double rotations                                            Example
• Two single rotations in opposite directions   • Rotating right around 30 will not help:
  (around two different nodes).                                            20 (2)
• Needed when there is a bend in the branch:
                              30                                  10                25 (2)


                        25                                                              30

                              27                                                27




                                                                                                         3
Example                                               Example
• First single left rotation around 25:           • First single left rotation around 25:
                  20 (2)                                                20 (2)


            10             30 (-2)                            10                 30 (-2)


                   25(1)                                                27 (-1)

                        27                                         25




                  Example                                     Which rotation?
• Then single right rotation around 30:           • Balance factor -2 (left subtree longer),
                  20 (1)                            balance factor of the left daughter -1 or 0:
                                                    single right rotation.
            10             27                     • Balance factor 2 (right subtree longer),
                                                    balance factor of the right daughter 1 or 0:
                   25           30                  single left rotation




            Which rotation?                              Deleting in AVL Trees
• Balance factor -2, balance factor of the left   • Find leftmost node/subtree of deleted node's
  daughter 1: double rotation, around the           right subtree.
  daughter to the left, around the root to the    • Delete leftmost subtree.
  right.                                          • Work back up to deleted node, restoring any
• Balance factor 2, balance factor of the right     imbalances.
  daughter -1: double rotation, around the        • Replace deleted node by leftmost subtree.
  daughter to the right, around the root to the   • Work back up to root, restoring any
  left.                                             imbalances.




                                                                                                   4
Number of rotations                                              Implementation?
• Insertion: balance can be restored with a               • Not really worth implementing, since not
  single rotation.                                          the most efficient balanced tree.
• Deletion: may require multiple rotations                • Have some pseudocode for computing
  (sometimes nodes are just marked as                       balance factors in
  deleted: lazy deletion).                                    www.cs.nott.ac.uk/~nza/G5BADS00/lecture13.html

• Overall performance: O(log N).
• On average, better than binary search trees.




             Red-Black Trees                              Example (black=grey, red=white)
                                                                                      30
• Red-black trees are binary search trees
  which come with additional information                                  15                          70
  about the nodes: the nodes are coloured red
  or black.
                                                                                20             60           85
  • The root is always black;                                        10

  • A red node cannot have red children;
  • Every path from the root to a null node (a leaf            5                     50             65 80        90
    or a node with only one child) should have the
    same number of black nodes.                           3
                                                                           40             55




              Non-example                                          Depth of Red-Black Trees
                          30
                                                          • The depth of a red-black tree is at most
             15                           70                2 log(N+1) (this can be shown by
                                                            induction).
                                                          • Intuitively, since we can pad some branches
        10          20             60           85
                                                            with red nodes and compose other branches
                                                            only of black ones, you expect the increase
   5                     50             65 80        90     in depth compared to perfectly balanced
                                                            trees (about twice longer…)
               40             55




                                                                                                                      5
Red-Black Trees insertion                                                        The idea
Insertion can be done top down, changing                  • If we need to insert an item in the red-black
  colours and rotating subtrees while                       tree, and we arrive at the insertion point
  searching for a place to insert the node. The             which is a node S which does not have at
  rules should be satisfied after the new node              least one of the daughters and S is black we
  is inserted. Only requires one pass through               are done: we insert our item as a red node
  the tree and is guaranteed to be O(log N).                and nothing changes.
                                                          • So make sure that whatever colour S was
                                                            before, when we arrive there it’s black.




          Example: insert 91                                              Example: insert 91
                          30                                                                   30

              15                          70                                   15                              70


         10         20             60           85                       10             20              60           85


   5                     50             65 80        90         5                             50             65 80             90


               40             55                                                   40              55                                91




                    Insertion                                       Example: single rotation 1
• Insert always as a red node
• If the parent in black, we are done                                         20                                          18

• If the parent is red, could perform a rotation                     18            22                           15             20
  with a colour change (see below)
                                                            15           19 21           23              10         16 19           22
• If the sibling of the parent node is black,
  this rotation solves the problem                                                                                             21        23
                                                           10       16
• If not, we are stuck, so we need to remove a
  possibility of two red siblings.




                                                                                                                                              6
Example: single rotation 2
              (problem)                                                    Top down insertion
                                                                  • On the way down, if we see a node X which
                  20                          18                    has two red children, make X red and
                                       15                           children black (if X is root, X will be
           18          22                          20
                                                                    recoloured black).
                                 10     16 19
   15        19 21          23                          22        • This preserves the number of black nodes
                                                                    on the path, but may not preserve the
                                                   21        23
 10     16                                                          property that there are no consecutive red
                                                                    nodes on any path.




           Example of a colour flip                                    Top down insertion contd.
                                                                  • Fix consecutive red nodes: perform a
             30                        30                           rotation with a colour change.
                                                                  • As in AVL trees, different kinds of rotations
      15          70              15          70
                                                                    depending on the kind of problem. Also
                                                                    involve colour change.

           60          85              60          85




             Java implementation                                                  Summary
• See Weiss, Chapter 19.5.3 (insertion only).                     • Binary search trees can become imbalanced,
                                                                    leading to inefficient search
• Code available on                                               • AVL trees and red-black trees: height
http://www.cs.fiu.edu/~weiss/dsaajava/Code/                         balanced binary search trees.
                                                                  • Leads to reasonable search complexity:
                                                                    O(log N).
                                                                  • Efficient (but complicated) algorithms for
                                                                    maintaing height balance under insertion
                                                                    and deletion.
                                                                  • Requires rotations and colour flips to
                                                                    restore balance.




                                                                                                                    7

Contenu connexe

Similaire à Balanced (18)

Avl tree
Avl treeAvl tree
Avl tree
 
Avl trees
Avl treesAvl trees
Avl trees
 
Avl tree ppt
Avl tree pptAvl tree ppt
Avl tree ppt
 
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDYAVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
AVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to doAVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to do
 
Avl tree
Avl treeAvl tree
Avl tree
 
Avl tree detailed
Avl tree detailedAvl tree detailed
Avl tree detailed
 
Lecture3
Lecture3Lecture3
Lecture3
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
3-avl-tree.ppt
3-avl-tree.ppt3-avl-tree.ppt
3-avl-tree.ppt
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
Study about AVL Tree & Operations
Study about AVL Tree & OperationsStudy about AVL Tree & Operations
Study about AVL Tree & Operations
 
Lect 13, 14 (final)AVL Tree and Rotations.pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdfLect 13, 14 (final)AVL Tree and Rotations.pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdf
 
Lecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfLecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdf
 
lec41.ppt
lec41.pptlec41.ppt
lec41.ppt
 

Dernier

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Dernier (20)

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
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
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Balanced

  • 1. Balanced Trees Solution • Binary search trees: if all levels filled, then • Keep the trees height balanced (for every search, insertion and deletion are O(log N). node, the difference in height between left • However, performance may deteriorate to and right subtrees at most 1) linear if nodes are inserted in order: • Performance always logarithmic. 10 11 12 Example How to keep the tree balanced Level 0 10 • Still need to insert preserving the order of 7 Level 1 13 keys (otherwise search does not work) Level 2 • Insert as the new items arrive (cannot wait 6 12 15 till have all items) Level 3 • So need to alter the tree as more items 14 arrive. Top down and bottom up Examples insertion • Top down insertion algorithms make • Bottom up: AVL trees changes to the tree (necessary to keep the • Top down: red-black trees tree balanced) as they search for the place to insert the item. They make one pass through the tree. • Exposition (not in Shaffer): follows • Bottom up: first insert the item, and then M.A.Weiss, Data structures and problem work back through the tree making changes. solving using Java, 2nd edition. Less efficient because make two passes through the tree. 1
  • 2. AVL Trees Non-example and example • AVL (Adelson-Velskii & Landis) trees are Not an AVL: AVL: binary search trees where nodes also have X (2) B additional information: the difference in depth between their left and right subtrees (balance factor). First example of balanced A B (1) X D trees. C D A C E • It is represented as a number equal to the depth of the right subtree minus the depth of E the left subtree. Can be 0,1 or -1. Depth of an AVL tree Insertion in AVL Trees • Calculating the maximal depth of an AVL • Insert new leaf node, as for ordinary binary tree is more difficult than calculating it for search tree. prefectly balanced or complete binary trees. • Then work back up from new leaf to root, • An (almost complete) calculation is given in checking if any height imbalance has been Weiss’s book (Ch.19.4.1). It gives introduced (computing new balance approximately 1.44 log(N+2) - 1.328 as the factors). upper bound on the height, so it’s O(log N). • Perform rotation to correct height imbalance • An average depth of a node in an AVL tree (which rotation depends on the balance is not established analytically yet. factor). Rotations Right rotation • The restructuring is done by performing a • Right rotation around X (tree is heavier on rotation. the left): • A rotation is performed around some node X (-2) X. It can be • single right rotation, A • single left rotation or B C • a double rotation. 2
  • 3. Right rotation Right rotation • Right rotation around X: • X moves down and to the right, into the position of its right child; X (-2) A • X's right subtree is unchanged. • X's left child A moves up to take X's place. A B X X is now A's new right child. • This leaves the old right child of A B C C unaccounted for. Since it comes from the left of X, it is less than X. So it becomes X's new left child. Left rotation Left rotation • The tree is heavier on the right: • Left rotation around X: X (2) X (2) B A B A B X D C D C D A C E E E Double rotations Example • Two single rotations in opposite directions • Rotating right around 30 will not help: (around two different nodes). 20 (2) • Needed when there is a bend in the branch: 30 10 25 (2) 25 30 27 27 3
  • 4. Example Example • First single left rotation around 25: • First single left rotation around 25: 20 (2) 20 (2) 10 30 (-2) 10 30 (-2) 25(1) 27 (-1) 27 25 Example Which rotation? • Then single right rotation around 30: • Balance factor -2 (left subtree longer), 20 (1) balance factor of the left daughter -1 or 0: single right rotation. 10 27 • Balance factor 2 (right subtree longer), balance factor of the right daughter 1 or 0: 25 30 single left rotation Which rotation? Deleting in AVL Trees • Balance factor -2, balance factor of the left • Find leftmost node/subtree of deleted node's daughter 1: double rotation, around the right subtree. daughter to the left, around the root to the • Delete leftmost subtree. right. • Work back up to deleted node, restoring any • Balance factor 2, balance factor of the right imbalances. daughter -1: double rotation, around the • Replace deleted node by leftmost subtree. daughter to the right, around the root to the • Work back up to root, restoring any left. imbalances. 4
  • 5. Number of rotations Implementation? • Insertion: balance can be restored with a • Not really worth implementing, since not single rotation. the most efficient balanced tree. • Deletion: may require multiple rotations • Have some pseudocode for computing (sometimes nodes are just marked as balance factors in deleted: lazy deletion). www.cs.nott.ac.uk/~nza/G5BADS00/lecture13.html • Overall performance: O(log N). • On average, better than binary search trees. Red-Black Trees Example (black=grey, red=white) 30 • Red-black trees are binary search trees which come with additional information 15 70 about the nodes: the nodes are coloured red or black. 20 60 85 • The root is always black; 10 • A red node cannot have red children; • Every path from the root to a null node (a leaf 5 50 65 80 90 or a node with only one child) should have the same number of black nodes. 3 40 55 Non-example Depth of Red-Black Trees 30 • The depth of a red-black tree is at most 15 70 2 log(N+1) (this can be shown by induction). • Intuitively, since we can pad some branches 10 20 60 85 with red nodes and compose other branches only of black ones, you expect the increase 5 50 65 80 90 in depth compared to perfectly balanced trees (about twice longer…) 40 55 5
  • 6. Red-Black Trees insertion The idea Insertion can be done top down, changing • If we need to insert an item in the red-black colours and rotating subtrees while tree, and we arrive at the insertion point searching for a place to insert the node. The which is a node S which does not have at rules should be satisfied after the new node least one of the daughters and S is black we is inserted. Only requires one pass through are done: we insert our item as a red node the tree and is guaranteed to be O(log N). and nothing changes. • So make sure that whatever colour S was before, when we arrive there it’s black. Example: insert 91 Example: insert 91 30 30 15 70 15 70 10 20 60 85 10 20 60 85 5 50 65 80 90 5 50 65 80 90 40 55 40 55 91 Insertion Example: single rotation 1 • Insert always as a red node • If the parent in black, we are done 20 18 • If the parent is red, could perform a rotation 18 22 15 20 with a colour change (see below) 15 19 21 23 10 16 19 22 • If the sibling of the parent node is black, this rotation solves the problem 21 23 10 16 • If not, we are stuck, so we need to remove a possibility of two red siblings. 6
  • 7. Example: single rotation 2 (problem) Top down insertion • On the way down, if we see a node X which 20 18 has two red children, make X red and 15 children black (if X is root, X will be 18 22 20 recoloured black). 10 16 19 15 19 21 23 22 • This preserves the number of black nodes on the path, but may not preserve the 21 23 10 16 property that there are no consecutive red nodes on any path. Example of a colour flip Top down insertion contd. • Fix consecutive red nodes: perform a 30 30 rotation with a colour change. • As in AVL trees, different kinds of rotations 15 70 15 70 depending on the kind of problem. Also involve colour change. 60 85 60 85 Java implementation Summary • See Weiss, Chapter 19.5.3 (insertion only). • Binary search trees can become imbalanced, leading to inefficient search • Code available on • AVL trees and red-black trees: height http://www.cs.fiu.edu/~weiss/dsaajava/Code/ balanced binary search trees. • Leads to reasonable search complexity: O(log N). • Efficient (but complicated) algorithms for maintaing height balance under insertion and deletion. • Requires rotations and colour flips to restore balance. 7