Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
AVL Trees
AVL Trees
AVL Tree – any binary search tree T that satisfies the height-balance
property is said to be an AVL Tree
44 4
17 2 56 3
If an AVL tree has n nodes,
what is the cost of
1 5 32 1 48 2 77 1 find, insert, remove ??
51 1
3
hR
hL
Proof: fix h, then find the corresponding min number of nodes in the tree
• h=1 ⇒ n=1
≥3
• h≥ ⇒ the tree contains the root and
- two AVL subtrees of heights (h-1), or
- one AVL subtree of height (h-1) and the other of height (h-2)
h h
h-1 h-1 h-1 h-2
h
h-1
6
∗) we obtain
Since nmin(h-1) > nmin(h-2), from (∗
1
nmin(h) > 2nmin(h-2)
1
nmin(h) > 4nmin(h-4)
h-2
nmin(h) > 8nmin(h-6)
∗ ∗)
(∗ nmin(h) > 2i ⋅nmin(h-2i), ∀ i such that h-2i ≥1
nmin(1) and nmin(2) are known, hence we will pick i such that h-2i = 1 or 2.
h h
−1 −1
∗) and (∗
From (∗ ∗ ∗) ⇒ n(h) ≥ nmin (h) > 2 2
nmin (1 or 2 ) ≥ 2 2
h2
n(h) = Ω 2
h < 2 ⋅ log(n) + 2
h(n) = O(log(n))
8
Proposition 2: An AVL tree with BF=0, for all nodes, cannot be become
unbalanced after a single insert / delete operation.
Types of Rotation
Y Z X
X Z Y Y
ZR XL
X Z
XL XR ZL ZR ZL XR
Single Left and Right Rotation preserve the inorder traversal ordering,
i.e. they preserve binary search tree property.
11
X Z X Y
YR YR
Z X
XL ZR XL ZL ZR YR
ZL ZR XL ZL
X Z y X
YL YL
Z X
XR ZL YL ZL ZR XR
ZL ZR ZR XR
Y BF=+2 X BF=-2
X BF=-1 Y BF=+1
h h
Z BF=-1
YL h
BF=-1 Z XR
h h
XR
h ZR YL
2 ZL ZR
ZL
N
N
Part 1: Insertion
Part 2: Rotation
T3 T4
T1 T2
N
rotated-st
21
Z |BF|=2 Y
Y |BF|=1 X Z
X |BF|=1
T4
T1 T2
T3 T3 T4
T1 T2 N
X |BF|=2 Y
Z |BF|=1 X Z
y |BF|=1
T1
T2 T3
T4 T1 T4
N
T2 T3
A |BF|=2 B |BF|<=1
h+1 h
T
T
24
Let us assume that an AVL Tree has become unbalanced after performing
removeAboveExternal(W).
44 Z
62 Y
17 62 Y
44 Z 78 X
32 50 78 X 17 50 88
48 54 88 48 54
Computation of BFs – find & store each node’s height in the node itself;
BF(v) = BF(rightChild(v).h) – BF(leftChild(v).h)
" cost of finding all BFs – O(n)
Method Time
size, isEmpty O(1)
findElement, insertItem, removeElement O(log(n))
findAllElements, removeAllElements O(log(n)+s)
s - size of returned iterator
findElement - O(log(n))
" has down-phase (search ) only
insertElement - O(log(n))
" initial findElement runs in O(log(n)) up
" restructuring up the tree runs in O(log(n)) down phase
" maintaining heights runs in O(log(n)) phase
28
Q.1 Assume that the following tree is a standard binary search tree
(sorted lexicographically). Draw this tree after the insertion of a new
node with element=R.
G S
P Y
Now, assume that the tree in the picture is an AVL tree. Draw the AVL
tree that will result when you insert a new node with element=R.
Finally, assume that the pictured above is an AVL tree. Draw the AVL
tree that will result when you insert a new node with element=T.