Академический Документы
Профессиональный Документы
Культура Документы
3 41
65 1
2 20
0 11
1
26
29
50 0
Lecture 6
vs.
Perfectly Balanced
Path
Lecture 6
k-1
Balance:
Worst when every node differs by 1 let Nh = (min.) # nodes in height-h AVL tree
= Nh = Nh1 + Nh2 + 1
> 2Nh2
= Nh > 2h/2
= h < 2 lg Nh
Alternatively:
Nh > Fh (nth Fibonacci number)
In fact Nh = Fn+1 1 (simple induction)
h
1+ 5
1.618 (golden ratio)
Fh = rounded to nearest integer where =
2
5
= max. h log n 1.440 lg n
Lecture 6
AVL Insert:
1. insert as in simple BST
2. work your way up tree, restoring AVL property (and updating heights as you go).
Each Step:
k-1
y
y
k-1
Left-Rotate(x)
k+1
k-1
k
k-1 B
k-1
y
z
k-1
k+1
Left-Rotate(x)
k+1
k
k
k-1
y
z
A
k
Right-Rotate(z)
Left-Rotate(x)
k+1
k+1
z
k-1
y
D
k-1
k-1
or
k-2
D k-1
k-1
B
or
k-2
Lecture 6
Insert(23)
3 41
65 1
2 20
0 11
41
50 0
1 29
0 11
0 23
Done
Insert(55)
3 41
3 41
2 20
65 1
2 20
50 0
1 26
0 11
29 0
0 23
0 23
Done
3 41
0 23
2 20
2 65
1 26
50 0
29 0
41
2 20
65 1
1 26
11
0
50 0
2 29
1 26
26
0
0 11
65 1
20
50 1
29 0
11
0
55 0
1 26
0 23
1 55
0 50
065
29 0
Comment 1. In general, process may need several rotations before done with an Insert.
Comment 2. Delete(-min) is similar harder but possible.
Lecture 6
AVL sort:
insert each item into AVL tree
(n lg n)
(n)
(n lg n)
in-order traversal
AVL Trees
B-Trees/2-3-4 Trees
BB[] Trees
Red-black Trees
(A) Splay-Trees
(R) Skip Lists
(A) Scapegoat Trees
(R) Treaps
(R) = use random numbers to make decisions fast with high probability
(A) = amortized: adding up costs for several operations = fast on average
For example, Splay Trees are a current research topic see 6.854 (Advanced Algorithms)
and 6.851 (Advanced Data Structures)
Big Picture:
Abstract Data Type(ADT): interface spec.
vs.
Data Structure (DS): algorithm for each op.
There are many possible DSs for one ADT. One example that we will discuss much later in
the course is the heap priority queue.
Priority Queue ADT
Q = new-empty-queue()
Q.insert(x)
x = Q.deletemin()
x = Q.findmin()
heap
(1)
(lg n)
(lg n)
(1)
AVL tree
(1)
(lg n)
(lg n)
(lg n) (1)
Lecture 6
Predecessor/Successor ADT
S = new-empty()
S.insert(x)
S.delete(x)
y = S.predecessor(x) nextsmaller
y = S.successor(x) next-larger
heap
(1)
(lg n)
(lg n)
(n)
AVL tree
(1)
(lg n)
(lg n)
(lg n)
(n)
(lg n)
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.