Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Motivation: we want to guarantee O(log n) running time on the find/insert/remove operations. Idea: keep the tree balanced after each operation. Solution: AVL (AdelsonVelskii and Landis) trees. AVL tree property: for every node in the tree, the height of the left and right subtrees differs by at most 1.
TCSS 342 AVL Trees v1.0 1
4
1 3 6 4 1 5 7 5 7
8
11
AVL tree
8 11
3
not an AVL tree 2
TCSS 342 AVL Trees v1.0 2
Idea: Cases 1 & 4 are solved by a single rotation. Cases 2 & 3 are solved by a double rotation.
TCSS 342 AVL Trees v1.0 4
15
20 21
Z
h+1 h
Y
h -1
X<b<Y<a<Z
b a
h+1 h h height h+2 after insert
Y
TCSS 342 AVL Trees v1.0
Z
6
Cases 2 & 3
a b
h
height h+2 before insert
Z
h
X Y
h+1
h -1
b
a
h
X
h+1
17 10 16
17 10 16
6
4 3 5
15 6 4 3 5 8 10 16 17
a b
h0 h
c Z W
h h-1
c
b
h-1
Y
X Z
10
Suppose T Sh, where h 2. Let TL and TR be Ts left and right subtrees. Since T has height h, either TL or TR has height h-1. Suppose its TR. By definition, both TL and TR are AVL trees. In fact, TR Sh-1 or else it could be replaced by a smaller AVL tree of height h-1 to give an AVL tree of height h that is smaller than T.
TCSS 342 AVL Trees v1.0 12
Similarly, TL Sh-2. Therefore, wh = 1 + wh-2 + wh-1 . Claim: For h 0, wh h , where = (1 + 5) / 2 1.6. Proof: The proof is by induction on h. Basis step: h=0. w0 = 1 = 0. h=1. w1 = 2 > 1. Induction step: Suppose the claim is true for 0 m h, where h 1.
13
Then wh+1 = 1 + wh-1 + wh 1 + h-1 + h (by the i.h.) = 1 + h-1 (1 + ) = 1 + h+1 (1+ = 2) > h+1 Thus, the claim is true. From the claim, in an n-node AVL tree of height h, n wh h (from the Claim) h log n = (log n) / (log ) < 1.441 log n
TCSS 342 AVL Trees v1.0 14