Dsa24 9
Dsa24 9
AVL Trees
Review of tree concepts
§ Basic tree concepts: general tree Hard to implement
B
A
C
B C D E
F D
F G H G E
I H
I J K J
K
4
A binary
search tree
³
5
12 18 20 23 35 44 52
7
Practice
Insert the numbers in the following sequence: 89, 27, 65, 34, 12, 90, 76, 38
89
27 90
12 65
34 76
38
Delete 65
8
Practice
Insert the numbers in the following sequence: 89, 27, 65, 34, 12, 90, 76, 38
89 89 89
27 90 27 90 27 90
12 65 12 38 12 76
34 76 34 76 34
38 38
Delete 65
9
§ Insertion: O(log2n)
§ Deletion: O(log2n) Only if the tree is well
balanced.
§ Search: O(log2n)
44 18
35 20
23 Search for 52 23
Search for 22
20 35
18 44
12 52
23
23
20 35
44
18 44 18
12 52 12 20 35 52
Balanced Trees
§ Problems of BST: the time complexity of
search, inserting and deleting with a BST can
vary between O(log2n) and O(n).
§ Unbalanced BST could cause the complexity to
be O(n) in the worst case, so we may get no
benefits (even worse for some operations) by
using BST compared to linear data structures.
§ The problem becomes how to make a BST to be
balanced.
12
Absolute
balance is
How to measure balance? impossible!
14
AVL Trees
§ An AVL tree (or height-balanced BST) is a
binary search tree such that
§ The heights of the left and right subtrees of the root
differ by at most one, i.e. |BF| =|HR-HL| £ 1.
§ each subtree of the tree is an AVL tree.
§ AVL tree is named after G. M. Adelson-Velskii
and E. M. Landis.
Causes of unbalance
§ A (nearly) balanced tree can become unbalanced due to
insertion and deletion operations on the tree:
§ Insert a node to the left subtree of a LH tree
§ Insert a node to the right subtree of a RH tree
insert a node
19
Causes of unbalance
§ Delete a node from the left subtree of a RH tree
§ Delete a node from the right subtree of a LH tree
Left of left Right of left Right of right Left of right
delete a node
20
RH RH
RH
RH EH RH
EH
EH EH Right of right
EH RH
EH
Turn left
EH
EH
EH RH EH RH EH EH
Left of right
EH EH EH
LH
Turn right
EH then turn left
Insertion
RH EH
RH
EH EH
EH RH
EH RH
EH EH LH EH LH EH RH
Right of right
EH
EH EH LH RH
Turn left
EH EH EH
EH EH EH EH
EH EH
RH
EH
https://www.cs.usfca.edu/~galles/visualization/AVLtree.html
32
§ AVL node
Readings
§ Read textbook Chapter 11
§ Read the code provided for you:
§ avlTree.h is easy to read but no deletion so can’t be
fully used for any applications.
§ AVL_ADT.h is a full implementation of AVL tree
structure.
§ I will explain the code for binary tree, BST, AVL tree at
PASS meeting next Monday.