02 Balanced Trees
02 Balanced Trees
Balanced Trees
The Searching Problem
(still)
2
We couldn't get a O(lg n) runtime for BST
3
2-3 trees
10 50
4
How does this help us?
10 10 25 50 50
5
How does this help us?
25
10 50
6
Searching a 2-3 tree
E J R X
A C H L P Q S Z
E J R X
A C H L P Q S Z
Push E up M
E J R X
Push C up
A C H K L P Q S Z
E M
C E J R X
A C D H K L P Q S Z
10
After put('D')
E M
C J R X
A D H K L P Q S Z
E R
C J P X
A D H K L O Q S Z
12
How to split in a 2-3 tree
13
Runtimes?
14
What about insert runtime?
● May need to search all the way down the tree to find the
appropriate leaf to add to
○ O(lg n)
● If inserting into a 3-node, need to split it
○ Runtime for a split?
● If we split and the parent is also a 3-node, need to split that
○ How many possible splits?
● See Proposition F in Section 3.3 of the text
15
So what's the catch?
16
Implementing 3-nodes with binary tree nodes
E J
A C H L
J
E
L
C H
A
17
Red-Black BSTs
18
Implementing 3-nodes with binary tree nodes
E J
A C H L
J
E
E
LL
C HH
A
A
19
Left-leaning red-black BST rules
● Have red and black links and satisfying the following three
restrictions:
○ Red links lean left.
○ No node has two red links connected to it.
○ The tree has perfect black balance
■ Every path from the root to a leaf link has the same
number of black links
● Black links are the links of a 2-3 tree, which we already
determined to be perfectly balanced
○ Hence, red-black BSTs will be perfectly balanced
according to their black links
20
Searching a red-black BST
Root
J
E
C H L
A
21
Inserting into a red-black BST
10
● If the next key is less, just make the left child red
10
5
22
Make the right child red then rotate the parent left
10
15
Rotate left
15
10
23
Implementing rotate left
def rotate_left(cur):
x = cur.right
cur.right = x.left
x.left = cur
x.is_red = cur.is_red
cur.is_red = True
return x 24
What about the next insert?
15
10
25
Inserting to the right of the root black node
15
10 10 15
● What should the 2-3 tree to look like after inserting 25?
○ Convert that to a red-black BST to see what our goal is
15 15
10 25 10 25
26
So how do we get there?
● Just like with inserting into a single black node, we're going
to descend the tree like BST insert, then add a new red link
15 15
10 10 25
● Now, to get this looking like our target, we'll use another
operation: the color flip
27
Color flip
15
15
10 25
10 25
15
15 10
10 5
● Insert 12 into:
15
15 10
10
12
15
12
10
30
And now…
31
What about larger trees?
33
Performance
34