Lab 7
Lab 7
Lab 7
AVL Tree
Quang D. C.
dungcamquang@tdtu.edu.vn
Note
In the previous lab, we learned how to build up a BST. And in this tutorial, we
continue to extend Binary Search Tree to the Balanced Binary Search Tree, one of
them called AVL Tree.
Part I
Classwork
In this part, lecturer will:
• During these part, students may ask any question that they don’t understand or
make mistakes. Lecturers can guide students, or do general guidance for the whole
class if the errors are common.
BinarySearchTrees.pptx
dungcamquang@tdtu.edu.vn 1
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022
4. Rotation
The insert or delete operation may make the AVL tree come to imbalance. A simple
modification of the tree, called rotation, can restore the AVL property. We have 4 types
dungcamquang@tdtu.edu.vn 2
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022
dungcamquang@tdtu.edu.vn 3
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022
This makes A come to the left subtree of B. And B replaces A to become the left
subtree of C.
dungcamquang@tdtu.edu.vn 4
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022
This makes C come to the right subtree of B. And B replaces C to become the right
subtree of A.
5. Balance
This is the code to re-balance the tree:
1 private Node balance (Node x) {
2 if ( checkBalance (x) < -1) {
3 if ( checkBalance (x. right ) > 0) {
4 x. right = rotateRight (x. right );
5 }
6 x = rotateLeft (x);
7 }
dungcamquang@tdtu.edu.vn 5
Ton Duc Thang University
Faculty of Information Technology Data Structures and Algorithms, Fall 2021-2022
Part II
Excercise
Responsibility of the students in this part:
Exercise 1
Complete the class to build the AVL tree. You can re-use the BST code in the
previous lab (insertion, deletion).
THE END
dungcamquang@tdtu.edu.vn 6