SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Downloaden Sie, um offline zu lesen
CS 16: Balanced Trees                                               CS 16: Balanced Trees




                                                                                 2-3-4 Trees Revealed
          2-3-4 Trees and Red-
               Black Trees                                                  • Nodes store 1, 2, or 3 keys and have
                                                                              2, 3, or 4 children, respectively
                                                                            • All leaves have the same depth

                                                                                                        k

                                                                                       beh                             nr



                                                                             a    cd     fg         i             lm   p    sx




                                                                             1
                                                                             -- log ( N + 1 ) ≤ height ≤ log ( N + 1 )
                                                                              -
                                                                             2



erm                               204                                 erm                               205




                          CS 16: Balanced Trees                                               CS 16: Balanced Trees




             2-3-4 Tree Nodes                                                           Why 2-3-4?
      • Introduction of nodes with more than 1 key,                         • Why not minimize height by maximizing
        and more than 2 children                                              children in a “d-tree”?
                                                                            • Let each node have d children so that we
                                                        a
2-node:                                                                         get O(log d N) search time! Right?


                                                                                                                                 logdN = log N/log d
      • same as a binary node
                                                  <a        >a

                                                   a b
3-node:
      • 2 keys, 3 links                      <a             >b
                                                       >a
                                                       <b                   • That means if d = N1/2, we get a height of 2
                                                                            • However, searching out the correct child
                                                  a b c                        on each level requires O(log N1/2) by
4-node:                                                                        binary search
      • 3 keys, 4 links
                                                                            • 2 log N1/2 = O(log N) which is not as good
                                   <a                            >c             as we had hoped for!
                                          >a                >b              • 2-3-4-trees will guarantee O(log N) height
                                          <b                <c                  using only 2, 3, or 4 children per node

erm                               206                                 erm                               207
CS 16: Balanced Trees                                                          CS 16: Balanced Trees




      Insertion into 2-3-4 Trees                                                       Top Down Insertion
                                                                                 • In our way down the tree, whenever we
      • Insert the new key at the lowest internal                                  reach a 4-node, we break it up into two 2-
        node reached in the search                                                 nodes, and move the middle element up
                                                                                   into the parent node
                                                                                    e                       e
         • 2-node becomes 3-node                                                            n                       fn

          g             d                                    dg
                                                                                       dfg                                                    g
                                                                                                                                       d


         • 3-node becomes 4-node

         f             dg                               d f g
                                                                            • Now we can perform the
                                                                              insertion using one of the                                     fn
                                                                              previous two cases
                                                                            • Since we follow this
                                                                              method from the root down                            de         g
      • What about a 4-node?
                                                                              to the leaf, it is called
         • We can’t insert another key!                                       top down insertion


erm                                 208                                    erm                                     209




                            CS 16: Balanced Trees                                                          CS 16: Balanced Trees




              Splitting the Tree
                                                                                             g                n
 As we travel down the tree, if we encounter any
 4-node we will break it up into 2-nodes. This
 guarantees that we will never have the problem                                                  c                          t
 of inserting the middle element of a former 4-
 node into its parent 4-node.
                                                                                         a           fil           pr              x

              g              c n t



                                        pr          x       Whoa, cowboy                                     n
               a        fil

                                                                                   g             c                          t
                   g                  n
                                                                                                                                           Whoa, cowboy

                                                                                         a           fil          pr               x
                        c                           t


                   a        fil            pr           x

erm                                 210                                    erm                                     211
CS 16: Balanced Trees                                                   CS 16: Balanced Trees




                                         n
                                                                                         Time Complexity of Insertion
            g                c                            t                                    in 2-3-4 Trees
                                                                          Whoa, cowboy
                        a        fil          pr                  x                      Time complexity:
                                                                                            • A search visits O(log N) nodes
                                       n
                                                                                               • An insertion requires O(log N) node splits
                                                                                               • Each node split takes constant time
        g                   ci                        t
                                                                                               • Hence, operations Search and Insert each
                                                                                                 take time O(log N)
                    a        f     l         pr                   x                      Notes:
                                                                                            • Instead of doing splits top-down, we can
                                         n                                                    perform them bottom-up starting at the in-
                                                                                              sertion node, and only when needed. This
                            ci                                t                               is called bottom-up insertion.
                                                                                               • A deletion can be performed by fusing
                                                                                                 nodes (inverse of splitting), and takes
                a           fg     l             pr                   x                          O(log N) time



erm                                            212                                       erm                           213




                                       CS 16: Balanced Trees                                                   CS 16: Balanced Trees




                Beyond 2-3-4 Trees                                                                     Red-Black Tree
                                                                                          A red-black tree is a binary search tree with the
What do we know about 2-3-4 Trees?                                                        following properties:
                                                                                               • edges are colored red or black
       • Balanced                                                            Siskel            • no two consecutive red edges
                                                                                                 on any root-leaf path
       • O(log N) search time                                                                  • same number of black edges
                                                                             Ebert               on any root-leaf path
                                                                                                 (= black height of the tree)
       • Different node structures                                          Roberto            • edges connecting leaves are black


Can we get 2-3-4 tree advantages in a binary                                                   Black                                   Red
                                                                                               Edge                                    Edge
              tree format???


      Welcome to the world of Red-Black Trees!!!




erm                                            214                                       erm                           215
CS 16: Balanced Trees                                           CS 16: Balanced Trees




          2-3-4 Tree Evolution                                   More Red-Black Tree
                                                                     Properties
Note how 2-3-4 trees relate to red-black trees               N   # of internal nodes
                                                             L   # leaves (= N + 1)
          2-3-4                                              H   height
                                        Red-Black
                                                             B   black height

                                                             Property 1: 2B ≤ N + 1 ≤ 4B




                                              or




                                                                                1
                                                             Property 2:        -- log ( N + 1 ) ≤ B ≤ log ( N + 1 )
                                                                                 -
                                                                                2
                                                             Property 3:        log ( N + 1 ) ≤ H ≤ 2 log ( N + 1 )
 Now we see red-black trees are just a way of
 representing 2-3-4 trees!                             This implies that searches take time O(logN)!
erm                           216                      erm                                    217




                      CS 16: Balanced Trees                                           CS 16: Balanced Trees




Insertion into Red-Black Trees                               Insertion - Plain and Simple
      1.Perform a standard search to find the leaf
        where the key should be added
                                                                     Let:
      2.Replace the leaf with an internal node with                             n be the new node
        the new key                                                             p be its parent
      3.Color the incoming edge of the new node                                 g be its grandparent
        red
      4.Add two new leaves, and color their
                                                       Case 1: Incoming edge of p is black
        incoming edges black
      5.If the parent had an incoming red edge, we
        now have two consecutive red edges! We          No violation
                                                                                  g
        must reorganize tree to remove that
        violation. What must be done depends on
        the sibling of the parent.                                          p                       STOP!

               R                                   R                 n
                                                                                              Pretty easy, huh?
G                                              G
                                                                                              Well... it gets messier...


erm                           218                      erm                                    219
CS 16: Balanced Trees                                                       CS 16: Balanced Trees




                  Restructuring                                                                More Rotations
Case 2: Incoming edge of p is red, and
         its sibling is black                                               Similar to a right rotation, we can do a
                                                                            “left rotation”...
      Uh oh!


                          g
                                              Much                                 g
                                              Better!               p
                  p                                                                                                                   p
                                                                                           p
                                                            n           g
              n                                                                                                                   g       n
                                                                                                   n



We call this a “right rotation”

      •   No further work on tree is necessary
                                                                                                       Simple, huh?
      •   Inorder remains unchanged
      •   Tree becomes more balanced
      •   No two consecutive red edges!
erm                                   220                                   erm                                   221




                              CS 16: Balanced Trees                                                       CS 16: Balanced Trees




               Double Rotations                                                        Last of the Rotations
What if the new node is between its parent and                                    And this would be called a
grandparent in the inorder sequence?                                                 “right-left double rotation”
We must perform a “double rotation”
(which is no more difficult than a “single” one)



                      g                                         n                  g                                                  n

              p                                         p               g                      p                             g            p


                  n                                                                    n



 This would be called a
    “left-right double rotation”


erm                                   222                                   erm                                   223
CS 16: Balanced Trees                                       CS 16: Balanced Trees




       Bottom-Up Rebalancing                                              Summary of Insertion
Case 3: Incoming edge of p is red and its
         sibling is also red

                                                                        • If two red edges are present, we do either
                                                                           • a restructuring (with a simple or double
                      g                                       g              rotation) and stop, or
                                                                           • a promotion and continue

              p                                           p             • A restructuring takes constant time and is
                                                                          performed at most once. It reorganizes an
                                                                          off-balanced section of the tree.
          n                                           n

                                                                        • Promotions may continue up the tree and
                                                                          are executed O(log N) times.

      • We call this a “promotion”                                      • The time complexity of an insertion is
      • Note how the black depth remains un-                              O(logN).
        changed for all of the descendants of g
      • This process will continue upward beyond
        g if necessary: rename g as n and repeat.

erm                                   224                         erm                             225




                              CS 16: Balanced Trees                                       CS 16: Balanced Trees




                  An Example                                                    A Cool Example
Start by inserting “REDSOX” into an empty tree                           C                E

                                                                                      D           R
                          E
                                                                                              O           S
                  D             R
                                                                                                                  X
                          O              S
                                                                                                  E
                                                X
                                                                                          D              R
 Now, let’s insert “C U B S”...
                                                                                  C               O               S


                                                                                                                      X
erm                                   226                         erm                             227
CS 16: Balanced Trees                                      CS 16: Balanced Trees




                                                                                            E
      An Unbelievable Example
      U                      E                                                      D                R

                     D               R
                                                                            C                  O                S

             C                O              S
                                                             Double Rotation                                            X

                               E                     X
                                                                                                            U
                         D              R                                                  E


                 C               O               S                              D                   R


                                                     X                  C                     O             U
              Oh No!
      What should we do?                                                                             S              X
                                                 U
erm                              228                         erm                            229




                         CS 16: Balanced Trees                                      CS 16: Balanced Trees




          A Beautiful Example                                                                                   E
                             E
      B                                                                                             D                   R
                     D                R
                                                             Rotation                     C                     O           U
              C                  O               U
                                                                                B                                       S       X
                                      S              X


                                     E                                                  E


                             D               R                                  C                R

What
now?                 C                 O             U                  B           D O                     U


             B                                   S       X                                       S                  X

erm                              230                         erm                            231
CS 16: Balanced Trees                                                 CS 16: Balanced Trees




                                                                                                       E
           A Super Example
                                   E
      S                                                                                         C               R

                          C                R
                                                                                           B        D O                 U
                                                                                      Use the
                  B           D O                     U                            Bat-Promoter!!
                                                                                                                S           X

                                            S             X
                                   E                                                                   E             S


                          C                 R                                                   C               R               BIFF!


                  B           D O                     U                                    B        D O                 U
                                                              We could’ve
Holy Consecutive                                              placed it on
                                                                                                                S
Red Edges, Batman!                           S            X                                                                 X
                                                              either side


                                                  S                                                                  S
erm                                    232                                   erm                            233




                              CS 16: Balanced Trees




                              E


                      C               R                   Rotation

              B           D O                 U


                                       S              X

                                           S

                                  R
The SUN lab
and Red-Bat
trees are safe...         E                U
   ...for now!!!

                  C           O S                     X


          B               D                 S

erm                                    234

Weitere ähnliche Inhalte

Andere mochten auch (6)

Del oral question
Del oral questionDel oral question
Del oral question
 
Tcp ip
Tcp ipTcp ip
Tcp ip
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Dcunit4 transmission media
Dcunit4 transmission mediaDcunit4 transmission media
Dcunit4 transmission media
 
Mpmc
MpmcMpmc
Mpmc
 
Pentium
PentiumPentium
Pentium
 

Mehr von Akshay Nagpurkar (19)

L6 mecse ncc
L6 mecse nccL6 mecse ncc
L6 mecse ncc
 
1.lan man wan
1.lan man wan1.lan man wan
1.lan man wan
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Ppl home assignment_unit4
Ppl home assignment_unit4Ppl home assignment_unit4
Ppl home assignment_unit4
 
Ppl home assignment_unit5
Ppl home assignment_unit5Ppl home assignment_unit5
Ppl home assignment_unit5
 
3 multiplexing-wdm
3 multiplexing-wdm3 multiplexing-wdm
3 multiplexing-wdm
 
2 multiplexing
2 multiplexing2 multiplexing
2 multiplexing
 
1 multiplexing
1 multiplexing1 multiplexing
1 multiplexing
 
Pcm pulse codemodulation-2
Pcm pulse codemodulation-2Pcm pulse codemodulation-2
Pcm pulse codemodulation-2
 
Modulation techniq of modem
Modulation techniq of modemModulation techniq of modem
Modulation techniq of modem
 
Ppl home assignment_unit3
Ppl home assignment_unit3Ppl home assignment_unit3
Ppl home assignment_unit3
 
Ppl home assignment_unit2
Ppl home assignment_unit2Ppl home assignment_unit2
Ppl home assignment_unit2
 
Ppl home assignment_unit1
Ppl home assignment_unit1Ppl home assignment_unit1
Ppl home assignment_unit1
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Pentium
PentiumPentium
Pentium
 
Real to protected_mode
Real to protected_modeReal to protected_mode
Real to protected_mode
 
Protection 80386
Protection 80386Protection 80386
Protection 80386
 
Privilege levels 80386
Privilege levels 80386Privilege levels 80386
Privilege levels 80386
 

Kürzlich hochgeladen

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

234 rb trees2x2

  • 1. CS 16: Balanced Trees CS 16: Balanced Trees 2-3-4 Trees Revealed 2-3-4 Trees and Red- Black Trees • Nodes store 1, 2, or 3 keys and have 2, 3, or 4 children, respectively • All leaves have the same depth k beh nr a cd fg i lm p sx 1 -- log ( N + 1 ) ≤ height ≤ log ( N + 1 ) - 2 erm 204 erm 205 CS 16: Balanced Trees CS 16: Balanced Trees 2-3-4 Tree Nodes Why 2-3-4? • Introduction of nodes with more than 1 key, • Why not minimize height by maximizing and more than 2 children children in a “d-tree”? • Let each node have d children so that we a 2-node: get O(log d N) search time! Right? logdN = log N/log d • same as a binary node <a >a a b 3-node: • 2 keys, 3 links <a >b >a <b • That means if d = N1/2, we get a height of 2 • However, searching out the correct child a b c on each level requires O(log N1/2) by 4-node: binary search • 3 keys, 4 links • 2 log N1/2 = O(log N) which is not as good <a >c as we had hoped for! >a >b • 2-3-4-trees will guarantee O(log N) height <b <c using only 2, 3, or 4 children per node erm 206 erm 207
  • 2. CS 16: Balanced Trees CS 16: Balanced Trees Insertion into 2-3-4 Trees Top Down Insertion • In our way down the tree, whenever we • Insert the new key at the lowest internal reach a 4-node, we break it up into two 2- node reached in the search nodes, and move the middle element up into the parent node e e • 2-node becomes 3-node n fn g d dg dfg g d • 3-node becomes 4-node f dg d f g • Now we can perform the insertion using one of the fn previous two cases • Since we follow this method from the root down de g • What about a 4-node? to the leaf, it is called • We can’t insert another key! top down insertion erm 208 erm 209 CS 16: Balanced Trees CS 16: Balanced Trees Splitting the Tree g n As we travel down the tree, if we encounter any 4-node we will break it up into 2-nodes. This guarantees that we will never have the problem c t of inserting the middle element of a former 4- node into its parent 4-node. a fil pr x g c n t pr x Whoa, cowboy n a fil g c t g n Whoa, cowboy a fil pr x c t a fil pr x erm 210 erm 211
  • 3. CS 16: Balanced Trees CS 16: Balanced Trees n Time Complexity of Insertion g c t in 2-3-4 Trees Whoa, cowboy a fil pr x Time complexity: • A search visits O(log N) nodes n • An insertion requires O(log N) node splits • Each node split takes constant time g ci t • Hence, operations Search and Insert each take time O(log N) a f l pr x Notes: • Instead of doing splits top-down, we can n perform them bottom-up starting at the in- sertion node, and only when needed. This ci t is called bottom-up insertion. • A deletion can be performed by fusing nodes (inverse of splitting), and takes a fg l pr x O(log N) time erm 212 erm 213 CS 16: Balanced Trees CS 16: Balanced Trees Beyond 2-3-4 Trees Red-Black Tree A red-black tree is a binary search tree with the What do we know about 2-3-4 Trees? following properties: • edges are colored red or black • Balanced Siskel • no two consecutive red edges on any root-leaf path • O(log N) search time • same number of black edges Ebert on any root-leaf path (= black height of the tree) • Different node structures Roberto • edges connecting leaves are black Can we get 2-3-4 tree advantages in a binary Black Red Edge Edge tree format??? Welcome to the world of Red-Black Trees!!! erm 214 erm 215
  • 4. CS 16: Balanced Trees CS 16: Balanced Trees 2-3-4 Tree Evolution More Red-Black Tree Properties Note how 2-3-4 trees relate to red-black trees N # of internal nodes L # leaves (= N + 1) 2-3-4 H height Red-Black B black height Property 1: 2B ≤ N + 1 ≤ 4B or 1 Property 2: -- log ( N + 1 ) ≤ B ≤ log ( N + 1 ) - 2 Property 3: log ( N + 1 ) ≤ H ≤ 2 log ( N + 1 ) Now we see red-black trees are just a way of representing 2-3-4 trees! This implies that searches take time O(logN)! erm 216 erm 217 CS 16: Balanced Trees CS 16: Balanced Trees Insertion into Red-Black Trees Insertion - Plain and Simple 1.Perform a standard search to find the leaf where the key should be added Let: 2.Replace the leaf with an internal node with n be the new node the new key p be its parent 3.Color the incoming edge of the new node g be its grandparent red 4.Add two new leaves, and color their Case 1: Incoming edge of p is black incoming edges black 5.If the parent had an incoming red edge, we now have two consecutive red edges! We No violation g must reorganize tree to remove that violation. What must be done depends on the sibling of the parent. p STOP! R R n Pretty easy, huh? G G Well... it gets messier... erm 218 erm 219
  • 5. CS 16: Balanced Trees CS 16: Balanced Trees Restructuring More Rotations Case 2: Incoming edge of p is red, and its sibling is black Similar to a right rotation, we can do a “left rotation”... Uh oh! g Much g Better! p p p p n g n g n n We call this a “right rotation” • No further work on tree is necessary Simple, huh? • Inorder remains unchanged • Tree becomes more balanced • No two consecutive red edges! erm 220 erm 221 CS 16: Balanced Trees CS 16: Balanced Trees Double Rotations Last of the Rotations What if the new node is between its parent and And this would be called a grandparent in the inorder sequence? “right-left double rotation” We must perform a “double rotation” (which is no more difficult than a “single” one) g n g n p p g p g p n n This would be called a “left-right double rotation” erm 222 erm 223
  • 6. CS 16: Balanced Trees CS 16: Balanced Trees Bottom-Up Rebalancing Summary of Insertion Case 3: Incoming edge of p is red and its sibling is also red • If two red edges are present, we do either • a restructuring (with a simple or double g g rotation) and stop, or • a promotion and continue p p • A restructuring takes constant time and is performed at most once. It reorganizes an off-balanced section of the tree. n n • Promotions may continue up the tree and are executed O(log N) times. • We call this a “promotion” • The time complexity of an insertion is • Note how the black depth remains un- O(logN). changed for all of the descendants of g • This process will continue upward beyond g if necessary: rename g as n and repeat. erm 224 erm 225 CS 16: Balanced Trees CS 16: Balanced Trees An Example A Cool Example Start by inserting “REDSOX” into an empty tree C E D R E O S D R X O S E X D R Now, let’s insert “C U B S”... C O S X erm 226 erm 227
  • 7. CS 16: Balanced Trees CS 16: Balanced Trees E An Unbelievable Example U E D R D R C O S C O S Double Rotation X E X U D R E C O S D R X C O U Oh No! What should we do? S X U erm 228 erm 229 CS 16: Balanced Trees CS 16: Balanced Trees A Beautiful Example E E B D R D R Rotation C O U C O U B S X S X E E D R C R What now? C O U B D O U B S X S X erm 230 erm 231
  • 8. CS 16: Balanced Trees CS 16: Balanced Trees E A Super Example E S C R C R B D O U Use the B D O U Bat-Promoter!! S X S X E E S C R C R BIFF! B D O U B D O U We could’ve Holy Consecutive placed it on S Red Edges, Batman! S X X either side S S erm 232 erm 233 CS 16: Balanced Trees E C R Rotation B D O U S X S R The SUN lab and Red-Bat trees are safe... E U ...for now!!! C O S X B D S erm 234