Docsity

Red-Black Trees: An Alternative Approach to Balanced Binary Search Trees, Slides of Data Structures and Algorithms

Partial preview of the text

Download Red-Black Trees: An Alternative Approach to Balanced Binary Search Trees and more Slides Data Structures and Algorithms in PDF only on Docsity!

CPSC 223

Algorithms & Data Abstract Structures

Lecture 20:

Red-black trees

Today …

• In-place mergesort

• Red-Black Trees

CPSC 223 -­‐-­‐ Fall 2010

Comments on AVL Trees

  • AVL vs other approaches
    • Rotations and traversals are hard to get right
    • But more importantly, the traversals create overhead
  • A Red Black tree is an alternative approach
    • In practice, (slightly) faster insertion and deletion
    • But (slightly) slower retrieval time
    • Red-black trees are typically implemented over AVL trees in practice CPSC 223 -­‐-­‐ Fall 2010

Red Black Trees [Bayer, 1972]

  • Basic idea
    • Further relax balancing constraints
    • Use a single top-down pass for insertion/deletion
    • Rebalance as part of this top-down pass
      • Unlike AVL where a bottom-up pass is needed to rebalance
    • Generally faster than an AVL tree (insertion and deletion)
    • Lookup/retrieve not as fast
      • Because height of tree can be longer … but still O (log n )

So how does this work?

CPSC 223 -­‐-­‐ Fall 2010

Properties of Red Black Trees

  • Since the root is black and there can not be 2

consecutive red nodes on a path …

  • The height of a Red Black tree is at most: 2*log 2 ( n +1)
  • Thus the height is O (log n )! How did we get this?
  • Notice that a root-leaf path can have at most 2 B nodes (i.e., h /2 ≤ B ≤ h ) 2 h /2^ – 1 ≤ 2 B^ – 1 ≤ n 2 h /2^ ≤ n + 1 h/2 ≤ log( n +1) h ≤ 2*log( n +1) CPSC 223 -­‐-­‐ Fall 2010

B = 2

Properties of Red Black Trees

  • Given a max height of 2log( n +1), is a Red Black tree

always “Balanced”?

  • Recall the balance factor must be -1, 0, or 1 for each node in a balanced binary tree
  • A Red Black tree technically is not balanced in this

way … but still has O (log n ) height

  • And this is what we really care about! CPSC 223 -­‐-­‐ Fall 2010

B = 2

This is a valid Red Black tree

Inserting Nodes

  • Always assign inserted nodes the color Red
    • If we assigned the node the color Black, we would create a path with more Black nodes than any other path
  • If the parent of the inserted node is Black, then we

are done!

  • Similar case if we are inserting the root
  • If the parent is Red, we violate Property 3
  • We now have to adjust the tree
  • … using tree rotations and color changes CPSC 223 -­‐-­‐ Fall 2010

Inserting Nodes

There are two approaches:

“Bottom-up” insertion

  • Similar to AVL by propagating changes up the tree

“Top-down” insertion

  • Optimization to avoid traversing back up the tree CPSC 223 -­‐-­‐ Fall 2010 We’ll only discuss the bottom up approach But look at a similar top-down approach later …