CPSC 221

Balanced Trees

Today

Announcements

  • Examlet 5 is this week: tree definitions and traversals
  • PA2 is due Monday 11/02


Today:

  • How tall is a BST?
  • Which tree makes you happiest?
  • Keeping a BST balanced: rotations, insert, remove

Recap

A dictionary is a structure supporting insert, find, and remove.

B_______ S_______ T_____ implementation of a dictionary incurs running time ________ for all of these.

dict<int> myT;
myT.insert(2);
myT.insert(7);
myT.insert(15);
myT.insert(22);
myT.insert(28);

How many “bad” \(n\)-item trees are there?

Binary search tree — height

38 13 51 10 25 40 84 12 37 66 89 95

Reminder: height(T) is

  • ______ if T is empty
  • 1 + max(height(TL), height(TR)), otherwise

The algorithms on BST depend on the height (\(h\)) of the tree.

The analysis should be in terms of the amount of data (\(n\)).

So we need relationships between \(h\) and \(n\):

\(h \ge f(n)\)

\(h \le g(n)\)

Binary tree (theory moments)

#1

What is the max number of nodes in a tree of height \(h\)?

What is the min height (\(h\)) for a tree of \(n\) nodes?

#2

What is the max height (\(h\)) for a tree of \(n\) nodes?

Thus: lower bound on height ______, upper bound on height ______ — good news or bad?

Your Turn

There are 7! = 5040 ways to insert the keys 1, 2, …, 7 into an empty BST.


How many of them build the perfect tree (height 2)?

How many build a stick (height 6)?

 

Guess what fraction for each.

All 5040

Average case!

The height of a BST depends on the order in which the data is inserted into it.

    ex.  1 3 2 4 5 7 6   vs.   4 2 3 6 7 1 5

How many different ways are there to insert \(n\) keys into a tree?

Avg height, over all arrangements of \(n\) keys, is ________.

operation avg case worst case sorted array sorted list
find \(\log n\) \(\log n\)
insert \(n\) \(n\)
delete \(n\) \(n\)
traverse \(n\) \(n\)

Which tree makes you happiest?

50 70 90 70 50 90

Idea:   _____________________________________________________________

The “height balance” of a tree T is:    \(b = \text{height}(T_R) - \text{height}(T_L)\)

A tree T is “height balanced” if:

  •  
  •  

Balanced Trees

A tree is height balanced if every node has \(b \in \{-1, 0, +1\}\).

A

2 1 4 3 7 6 5 9 11 12 10 8

B

20 40 30 60 85 95 99 90 80 50

Pause the video.   Label every node with its balance \(b\).   Which tree is height balanced?

Insert 95

Before: balanced

20 40 30 60 85 99 90 80 50

After: not

20 40 30 60 85 95 99 90 80 +2 50 +2

Only nodes on the path from 95 up to the root can change balance. Fix the lowest one: 80.

Left rotation

60 85 95 99 90 80 +2

Left rotation, in general

Before

s t T1 T2 T3 20 10

After

t s T1 T2 10 T3 20
void rotateLeft(Node *& t) {
    Node * s = t->right;
    t->right = _______;
    s->left  = _______;
    t        = _______;
    updateHeight(t->left);
    updateHeight(t);
}
int height(Node * t) {
    return t == nullptr ? -1 : t->height;
}
void updateHeight(Node * t) {
    t->height = 1 + max(height(t->left), height(t->right));
}

Your Turn

We just inserted 60.

a) Where is the imbalance?
b) What type of rotation should fix it?
c) Perform that rotation.

Before

20 60 50 40 80 70

After

Double rotation

20 60 50 40 +1 80 70 −2
20 40 60 50 80 70 −2
20 40 60 80 70 50

Bent stick  →  rotateLeft about 40 straightens it  →  a stick  →  rotateRight about 70  →  a mountain

A left-right rotation.

Balanced trees: summary

Rotations:

  • four kinds: left, right, left-right, right-left (mirror images)
  • local: whole subtrees move; nothing inside them changes
  • constant time: a few pointer changes and height updates
  • the BST property is kept: the in-order traversal doesn’t change


GOAL: use rotations to keep a BST height balanced, on every insert and remove.


Height-balanced BSTs, kept that way by rotations, have a special name:   AVL trees


Still to work out:   Which rotation?   Where in the code?

Which rotation?

T1 T2 T3 x T4 T5 y r t

An insert into t’s right subtree made \(b = +2\) at t.

If it went into T4 or T5, a __________ rotation about t fixes it.

    We can tell: balance at t->right is ____

If it went into T2 or T3, a __________ rotation about t fixes it.

    We can tell: balance at t->right is ____

AVL insert

void insert(Node *& t, const K & key) {
    if (t == nullptr)
        t = new Node(key);
    else if (key < t->key)
        insert(t->left, key);
    else if (key > t->key)
        insert(t->right, key);
    rebalance(t);
}

Lecture 18’s insert, plus one line.

void rebalance(Node *& t) {
    int b = balance(t);
    if (b == 2) {
        if (balance(t->right) >= 0)
            rotate__________(t);
        else
            rotate__________(t);
    }
    else if (b == -2) {
        if (balance(t->left) <= 0)
            rotate__________(t);
        else
            rotate__________(t);
    }
    else updateHeight(t);
}

Your Turn

Insert 1, 2, 3, 4, 5, 6, 7, in that order, into an empty AVL tree.


Draw the tree after each insert.


What tree do you end up with?

Watch it

AVL remove

2 1 4 3 7 6 5 9 11 12 10 8

Remove as in a BST, then rebalance every node on the path back up to the root.

T.remove(9);   What happens?

Watch it

Next time

AVL analysis: why is the height of an AVL tree \(O(\log n)\)?


operation BST, worst case AVL tree
find \(n\)
insert \(n\)
remove \(n\)