סיבוב ימינה
שיעור 7 מתוך 16 בקורס עץ AVL – סדרת מבני נתונים מס' 10 של Coddy.
כאשר הצד השמאלי של צומת גבוה מדי, סיבוב ימינה מתקן זאת. נסמן את הצומת הלא מאוזן ב-y ואת הבן השמאלי שלו ב-x. הסיבוב מקדם את x למקומו של y: x הופך לשורש החדש של תת-העץ, y הופך לבן הימני של x, ותת-העץ הימני הישן של x (נסמן אותו ב-T2) מתחבר מחדש בתור הבן השמאלי החדש של y, שכן כל ערך ב-T2 עדיין גדול מ-x וקטן מ-y.
לאחר חיבור המצביעים מחדש, יש לחשב מחדש את height גם של y וגם של x, תחילה של y, מכיוון שכעת הוא נמוך יותר בעץ.
אתגר
קלכתוב מתודה rotateRight(y) במחלקה AVLTree. נגדיר x = y.left ו-T2 = x.right. קבע x.right = y ו-y.left = T2, חשב מחדש את ה-height של y ואז של x לפי 1 + max(getHeight(left), getHeight(right)), והחזר את x כשורש תת-העץ החדש.
נסו בעצמכם
#include <stdio.h>
#include <string.h>
#include "avltree.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (strcmp(line, "1") == 0) {
Node* y = Node_create(30);
y->height = 3;
Node* x = Node_create(20);
x->height = 2;
Node* t1 = Node_create(10);
t1->height = 1;
x->left = t1;
y->left = x;
Node* newRoot = AVLTree_rotateRight(tree, y);
printf("%d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value);
}
if (strcmp(line, "2") == 0) {
Node* y = Node_create(50);
y->height = 3;
Node* x = Node_create(30);
x->height = 2;
x->left = Node_create(20);
x->left->height = 1;
x->right = Node_create(40);
x->right->height = 1;
y->left = x;
y->right = Node_create(60);
y->right->height = 1;
Node* newRoot = AVLTree_rotateRight(tree, y);
printf("%d %d %d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value, newRoot->right->left->value, newRoot->right->right->value);
}
}
return 0;
}
כל השיעורים ביחידה עץ AVL – סדרת מבני נתונים מס' 10
תרגלו בעצמכם: קומפיילר C אונליין