CSC 2100 B Tutorial 5 AVL Tree 26
CSC 2100 B Tutorial 5 AVL Tree 26 FEB, 2008 1
AVL tree For each node, the difference of height between left and right are no more than 1. struct AVLnode_s { Datatype element; int height; struct AVLnode *left; struct AVLnode *right; }; typedef struct AVLnode_s AVLnode; 2
Four Models l There are four models about the operation of AVL Tree: LL RR LR RL 3
AVL tree l Single rotation: left-left (LL) k 2 k 1 k 2 Z X W Y Z 4
AVL tree l Single rotation: right-right (RR) k 1 k 2 X k 1 Z Y Z X W Y W 5
AVL tree l Double rotation: left-right (LR) k 3 k 2 k 1 k 3 D k 2 A A B C D 6
AVL tree l Double rotation: right-left (RL) k 1 k 2 k 3 A k 1 k 3 k 2 D A B B C D C 7
Balancing an AVL tree after an insertion l Begin at the node containing the item which was just inserted and move back along the access path toward the root. { l For each node determine its height and check the balance condition. { l If the height of the current node does not increase, then the tree is AVL balanced and no further nodes need be considered. l else If the node has become unbalanced, a rotation is needed to balance it. l l After the rotation, the height of the node remains unchanged, the tree is AVL balanced and no further nodes need be considered. Otherwise, the height of the node increases by one, but no rotation is needed. } we proceed to the next node on the access path. } 8
AVLnode *insert(Datatype x, AVLnode *t) { if (t == NULL) { /* Create. New. Node */ } else if (x < t->element) { t->left = insert(x, t->left); /* Do. Left */ } else if (x > t->element) { t->right = insert(x, t->right); /* Do. Right */ } t->height = max(height(t->left), height(t->right)) + 1; } 9
AVL tree l Create. New. Node t = malloc(sizeof(struct AVLnode); t->element = x; t->height = 0; t->left = NULL; t->right = NULL; 10
AVL tree l Do. Left if (height(t->left) - height(t->right) == 2) if (x < t->left->element) t = single. Rotate. With. Left(t); // LL else t = double. Rotate. With. Left(t); // LR 11
AVL tree l Do. Right if (height(t->right) - height(t->left) == 2) if (x > t->right->element) t = single. Rotate. With. Right(t); // RR else t = double. Rotate. With. Right(t); // RL 12
AVL tree l A Java applet showing AVL tree operations at http: //webpages. ull. es/users/jriera/Docencia/AVL%20 tre e%20 applet. htm 13
AVL tree l Initial tree 14
AVL tree l Insert 32 (Single rotation: left) k 2 k 1 X 32 15
AVL tree l After insert 32 k 1 X k 2 16
AVL tree l Insert 37 (Double rotation: left-right) k 3 k 1 k 2 B 37 17
AVL tree l After insert 37 k 2 k 1 k 3 B 18
AVL tree l Insert 60 (Single rotation: right) k 1 k 2 Z 60 19
AVL tree l After insert 60 k 2 k 1 Z 20
Thank you! Q&A? 21
- Slides: 21