SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Ă„hnlich wie Balanced

Ă„hnlich wie 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
 

KĂĽrzlich hochgeladen

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
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
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
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
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
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
 
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
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
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
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 

KĂĽrzlich hochgeladen (20)

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.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
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
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
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
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
 
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)
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.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
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 

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