Professional Documents
Culture Documents
! Todays Topics: " Balanced Search Trees # AVL Trees and Rotations # Splay trees ! Covered in Chapter 4 of the text
at every node
" Height of an empty subtree is defined to be -1
! Implementation: Store current heights in each node and
6 3 Heights 1 4 1 0 9 2 7 1 8 0
6 3 Heights 1 4 1 0 9 2 7 1 8 0
-1 6 1 4 0 1 9
Balance factors
1-(-1) = 2
7 (-1)-0 = -1 8 0
No! Aint ALV.
Why AVL?
! Can prove: Height of an AVL tree of N nodes is always
6 0 0 4 0 1 9 1 5 8 0 0 1 4 Height = O(log N) 0 1
6 0 7 -1 0 9
Insert Example
No longer an AVL tree 6 0 1 5 0 4 7 -1 0 9 Insert 3 6 1
2
1 4 0 3
7 -1 0 9
Problem: Insert may cause balance factor to become 2 or 2 for some node on the path from insertion point to root node
R. Rao, CSE 326 6
Restoring Balance
! Idea: After Inserting the new node,
1. Back up to root updating heights along the access path 2. If Balance Factor = 2 or 2, adjust tree by rotation around deepest such node. 6 1
2
1 4 0 3
R. Rao, CSE 326
7 -1 0 9
6 0 1 5 0 4 7 -1 0 9
Insert 3
6 1
Rotate 0 4 0 3
6 0 7 -1 5 0 AVL 9 0
2
1 4 0 3
7 -1 0 9
AVL
Not AVL
BF = 1 BF = 1 BF = 0 BF = 0 BF = 0 BF = 0 BF = 0 BF = 0 BF = 0
Outside Case
BF = ? BF = ? BF = ? BF = ? BF = 0 BF = 0 BF = 0
10
Inside Case
BF = BF = BF = BF = BF = 0 BF = BF = BF = BF = BF =
11
j Z
k X
R. Rao, CSE 326
Y
13
j Z Y
k X
R. Rao, CSE 326 14
j k
Do a right rotation
Z Y X
R. Rao, CSE 326 15
j k
Z Y X
R. Rao, CSE 326 16
k j X
R. Rao, CSE 326
Z
17
j Z
k X
R. Rao, CSE 326
Y
18
j k
Z X
R. Rao, CSE 326
Y
19
k j X Z Y
R. Rao, CSE 326
20
j Z
k X
R. Rao, CSE 326
Y
21
j i Z W
22
k X V
R. Rao, CSE 326
j k X V
R. Rao, CSE 326
i W
23
i k W X
R. Rao, CSE 326
Z V
24
i j W
k X
R. Rao, CSE 326
Z
25
4 3 6
26
28
Splay Trees
Splay trees are tree structures that: 1. Are not perfectly balanced all the time 2. Allow actual Find operations to balance the tree so that future operations may run faster Based on the heuristic: If X is accessed once, it is likely to be accessed again. - After node X is accessed, perform splaying operations to bring X up to the root of the tree. - Do this in a way that leaves the tree more balanced as a whole.
R. Rao, CSE 326 29
After Find(R)
Splay Idea: Get R up to the root using rotations
30
G P X P
G P
X
31
element left
right
parent
2. When X is accessed, apply one of six rotation operations: Single Rotations (X has a P but no G) zig-left, zig-right Double Rotations (X has both a P and a G) zig-zig-left, zig-zig-right zig-zag-left, zig-zag-right
R. Rao, CSE 326 32
Zig-right
Zig-left
Zig (Zig-right)
Zig (Zig-right)
! Again, due to zig-zig splaying, R has bubbled to the top! ! Note: Parent-Grandparent rotated first.
R. Rao, CSE 326 35
Zig (Zig-left)
Zag (Zig-right)
36
37
tree.
! What happens when you access 7?
38